Spaces:
Sleeping
Sleeping
Multi-agent updates
Browse files- .gitignore +6 -0
- .hfignore +8 -0
- APP_FLOW.md +100 -0
- CONTRIBUTING.md +64 -15
- DEPLOYMENT.md +113 -0
- MakeFile.mak +28 -34
- README.md +163 -31
- TRAVEL_PROMPT_FEATURE.md +38 -0
- app.py +1454 -490
- diagnosis_engine/__init__.py +24 -0
- diagnosis_engine/collapse.py +47 -0
- diagnosis_engine/diagnosis_agent.py +129 -0
- diagnosis_engine/faiss_index.py +53 -0
- diagnosis_engine/prevalence.py +103 -0
- diagnosis_engine/reranker.py +118 -0
- diagnosis_engine/scoring.py +147 -0
- diagnosis_engine/tfidf.py +27 -0
- diagnosis_engine/tropical_diseases.py +20 -0
- diagnosis_engine/vocabulary.py +83 -0
- eval/real_query_runner.py +99 -0
- eval/real_symptom_queries.json +108 -0
- pytest.ini +2 -0
- requirements.txt +8 -25
- scripts/evaluate_real_queries.py +21 -0
- scripts/smoke_check.py +52 -0
- tests/conftest.py +38 -0
- tests/test_chat_flow.py +120 -0
- tests/test_helpers.py +59 -0
- tests/test_real_symptom_queries.py +28 -0
.gitignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
.env.*
|
| 3 |
+
logs/
|
| 4 |
+
faiss_store/
|
| 5 |
+
__pycache__/
|
| 6 |
+
*.pyc
|
.hfignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
.env.*
|
| 3 |
+
logs/
|
| 4 |
+
faiss_store/
|
| 5 |
+
__pycache__/
|
| 6 |
+
*.pyc
|
| 7 |
+
tests/
|
| 8 |
+
eval/
|
APP_FLOW.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# App Flow Diagram
|
| 2 |
+
|
| 3 |
+
This diagram shows the main code path for starting the app and processing a user prompt.
|
| 4 |
+
|
| 5 |
+
## Startup and Prompt Flow
|
| 6 |
+
|
| 7 |
+
```mermaid
|
| 8 |
+
flowchart TD
|
| 9 |
+
A["python app.py"] --> B["MedicalChatbotApp()"]
|
| 10 |
+
B --> C["load_datasets()"]
|
| 11 |
+
C --> D["Create agents"]
|
| 12 |
+
D --> D1["DiseaseDiagnosisAgent"]
|
| 13 |
+
D --> D2["ClarificationAgent"]
|
| 14 |
+
D --> D3["SymptomSeverityAgent"]
|
| 15 |
+
D --> D4["DiseaseDescriptionAgent"]
|
| 16 |
+
D --> D5["PrecautionAdvisorAgent"]
|
| 17 |
+
D1 --> E["build_faiss_index(df)"]
|
| 18 |
+
D1 --> F["build_tfidf_matrix(collapsed_df)"]
|
| 19 |
+
D --> G["ReActRouter(agents, all_symptoms)"]
|
| 20 |
+
G --> H["launch()"]
|
| 21 |
+
H --> I["Gradio UI shown"]
|
| 22 |
+
|
| 23 |
+
I --> J["User submits prompt"]
|
| 24 |
+
J --> K["respond(msg, state)"]
|
| 25 |
+
K --> L["chat(user_input, session_state)"]
|
| 26 |
+
L --> M["extract_structured_context()"]
|
| 27 |
+
M --> N["merge_structured_context()"]
|
| 28 |
+
N --> O["router.plan(user_input, history, structured_context)"]
|
| 29 |
+
|
| 30 |
+
O --> P{"Planner output valid?"}
|
| 31 |
+
P -- "Yes" --> Q["Executable steps"]
|
| 32 |
+
P -- "No" --> R["router._fallback_plan()"]
|
| 33 |
+
R --> Q
|
| 34 |
+
|
| 35 |
+
Q --> S["_execute_plan()"]
|
| 36 |
+
S --> T{"Agent step type"}
|
| 37 |
+
T -- "clarification_agent" --> U["ClarificationAgent.handle()"]
|
| 38 |
+
T -- "symptom_severity" --> V["SymptomSeverityAgent.handle()"]
|
| 39 |
+
T -- "disease_diagnosis" --> W["DiseaseDiagnosisAgent.handle()"]
|
| 40 |
+
T -- "disease_description" --> X["DiseaseDescriptionAgent.handle()"]
|
| 41 |
+
T -- "precaution_advisor" --> Y["PrecautionAdvisorAgent.handle()"]
|
| 42 |
+
|
| 43 |
+
W --> W1["normalize_symptom() / map_to_known_symptoms()"]
|
| 44 |
+
W1 --> W2["build_user_vector()"]
|
| 45 |
+
W1 --> W3["build_user_tfidf_vector()"]
|
| 46 |
+
W2 --> W4["FAISS search"]
|
| 47 |
+
W3 --> W5["score_candidates()"]
|
| 48 |
+
W4 --> W5
|
| 49 |
+
W5 --> W6{"Top scores close?"}
|
| 50 |
+
W6 -- "Yes" --> W7["LLMReranker.rerank()"]
|
| 51 |
+
W6 -- "No" --> W8["Keep scored ranking"]
|
| 52 |
+
W7 --> Z["diagnosis result"]
|
| 53 |
+
W8 --> Z
|
| 54 |
+
|
| 55 |
+
U --> AA["clarification result"]
|
| 56 |
+
V --> AB["severity result"]
|
| 57 |
+
X --> AC["description result"]
|
| 58 |
+
Y --> AD["precaution result"]
|
| 59 |
+
Z --> AE["Format answer"]
|
| 60 |
+
AA --> AE
|
| 61 |
+
AB --> AE
|
| 62 |
+
AC --> AE
|
| 63 |
+
AD --> AE
|
| 64 |
+
|
| 65 |
+
AE --> AF{"Red flags or ambiguity?"}
|
| 66 |
+
AF -- "Emergency" --> AG["_format_emergency_answer()"]
|
| 67 |
+
AF -- "Needs clarification" --> AH["_format_clarification_answer()"]
|
| 68 |
+
AF -- "Diagnosis/details" --> AI["_format_diagnosis_answer() or detail response"]
|
| 69 |
+
|
| 70 |
+
AG --> AJ["Update session state"]
|
| 71 |
+
AH --> AJ
|
| 72 |
+
AI --> AJ
|
| 73 |
+
AJ --> AK["_render_session_summary()"]
|
| 74 |
+
AJ --> AL["_render_result_card()"]
|
| 75 |
+
AK --> AM["Return history, state, summary, card_html"]
|
| 76 |
+
AL --> AM
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
## Main Files Involved
|
| 80 |
+
|
| 81 |
+
- `app.py`: app startup, router, session state, prompt processing, response formatting, and Gradio UI
|
| 82 |
+
- `diagnosis_engine/diagnosis_agent.py`: diagnosis pipeline orchestration
|
| 83 |
+
- `diagnosis_engine/faiss_index.py`: symptom vector indexing and retrieval
|
| 84 |
+
- `diagnosis_engine/tfidf.py`: TF-IDF symptom similarity
|
| 85 |
+
- `diagnosis_engine/scoring.py`: candidate scoring and ranking
|
| 86 |
+
- `diagnosis_engine/vocabulary.py`: symptom normalization and synonym mapping
|
| 87 |
+
- `diagnosis_engine/reranker.py`: optional LLM reranking for close candidates
|
| 88 |
+
|
| 89 |
+
## Practical Reading Order
|
| 90 |
+
|
| 91 |
+
If you want to trace the code manually, this is the most useful order:
|
| 92 |
+
|
| 93 |
+
1. `app.py` -> `MedicalChatbotApp.__init__()`
|
| 94 |
+
2. `app.py` -> `launch()`
|
| 95 |
+
3. `app.py` -> `chat()`
|
| 96 |
+
4. `app.py` -> `ReActRouter.plan()`
|
| 97 |
+
5. `app.py` -> `_execute_plan()`
|
| 98 |
+
6. `diagnosis_engine/diagnosis_agent.py` -> `handle()`
|
| 99 |
+
7. `diagnosis_engine/scoring.py` -> `score_candidates()`
|
| 100 |
+
8. `app.py` -> `_format_*_answer()` methods
|
CONTRIBUTING.md
CHANGED
|
@@ -1,15 +1,64 @@
|
|
| 1 |
-
# Contributing to MediBot
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
``
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributing to MediBot
|
| 2 |
+
|
| 3 |
+
Thanks for helping improve MediBot.
|
| 4 |
+
|
| 5 |
+
## Development Setup
|
| 6 |
+
|
| 7 |
+
1. Clone the repository.
|
| 8 |
+
2. Create and activate a virtual environment.
|
| 9 |
+
3. Install runtime dependencies from `requirements.txt`.
|
| 10 |
+
4. Install development dependencies from `requirements-dev.txt`.
|
| 11 |
+
5. Set `OPENAI_API_KEY` in your environment or a local `.env` file.
|
| 12 |
+
|
| 13 |
+
Example:
|
| 14 |
+
|
| 15 |
+
```bash
|
| 16 |
+
python -m venv .venv
|
| 17 |
+
.venv\Scripts\activate
|
| 18 |
+
pip install -r requirements.txt
|
| 19 |
+
pip install -r requirements-dev.txt
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
Optional helper commands are available in `MakeFile.mak`.
|
| 23 |
+
|
| 24 |
+
## Before Opening a PR
|
| 25 |
+
|
| 26 |
+
Run the lightweight checks:
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
python scripts/smoke_check.py
|
| 30 |
+
python scripts/evaluate_real_queries.py
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Run tests:
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
.venv\Scripts\python.exe -m pytest tests -q
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Or use:
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
make -f MakeFile.mak smoke-check
|
| 43 |
+
make -f MakeFile.mak eval
|
| 44 |
+
make -f MakeFile.mak test
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
## Project Areas
|
| 48 |
+
|
| 49 |
+
- `app.py`: routing, session state, response formatting, Gradio UI
|
| 50 |
+
- `diagnosis_engine/`: retrieval, scoring, prevalence priors, reranking, symptom mapping
|
| 51 |
+
- `data/`: symptom, severity, description, and precaution datasets
|
| 52 |
+
- `eval/`: deterministic real-query evaluation cases
|
| 53 |
+
- `tests/`: pytest coverage
|
| 54 |
+
|
| 55 |
+
## Contribution Guidelines
|
| 56 |
+
|
| 57 |
+
- keep changes aligned with the app's educational, non-diagnostic scope
|
| 58 |
+
- preserve emergency escalation behavior for red-flag symptoms
|
| 59 |
+
- prefer adding or updating tests when changing routing, symptom mapping, or scoring
|
| 60 |
+
- document user-facing behavior changes in the relevant markdown notes when needed
|
| 61 |
+
|
| 62 |
+
## License
|
| 63 |
+
|
| 64 |
+
MediBot is released under the MIT License. See [LICENSE](LICENSE).
|
DEPLOYMENT.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Deployment Guide
|
| 2 |
+
|
| 3 |
+
## Target
|
| 4 |
+
|
| 5 |
+
This project is set up to run as a Hugging Face Space using:
|
| 6 |
+
|
| 7 |
+
- `sdk: gradio`
|
| 8 |
+
- `app_file: app.py`
|
| 9 |
+
- Python 3.12
|
| 10 |
+
|
| 11 |
+
The Space metadata lives at the top of [README.md](README.md).
|
| 12 |
+
|
| 13 |
+
## Pre-Deployment Checklist
|
| 14 |
+
|
| 15 |
+
Before pushing to Hugging Face:
|
| 16 |
+
|
| 17 |
+
1. Install dependencies locally.
|
| 18 |
+
2. Set `OPENAI_API_KEY` in your environment or local `.env`.
|
| 19 |
+
3. Run the lightweight checks:
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
python scripts/smoke_check.py
|
| 23 |
+
python scripts/evaluate_real_queries.py
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
4. Optionally run the full test suite:
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
.venv\Scripts\python.exe -m pytest tests -q
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
5. Confirm the app starts locally:
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
python app.py
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
If you use `make`, you can also run:
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
make -f MakeFile.mak deploy-check
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
## Hugging Face Space Setup
|
| 45 |
+
|
| 46 |
+
In your Hugging Face Space:
|
| 47 |
+
|
| 48 |
+
1. Create a new Gradio Space.
|
| 49 |
+
2. Push this repository to the Space.
|
| 50 |
+
3. Add `OPENAI_API_KEY` as a Space Secret.
|
| 51 |
+
4. Make sure `requirements.txt` is present at the repo root.
|
| 52 |
+
5. Confirm the Space is using the metadata block in `README.md`.
|
| 53 |
+
6. Keep `.hfignore` in the repo so test and local-only files are not uploaded to the Space.
|
| 54 |
+
|
| 55 |
+
## Files Required for Deployment
|
| 56 |
+
|
| 57 |
+
These files and directories should be present in the deployed repo:
|
| 58 |
+
|
| 59 |
+
- `app.py`
|
| 60 |
+
- `requirements.txt`
|
| 61 |
+
- `README.md`
|
| 62 |
+
- `data/`
|
| 63 |
+
- `diagnosis_engine/`
|
| 64 |
+
- `static/`
|
| 65 |
+
|
| 66 |
+
Optional but useful:
|
| 67 |
+
|
| 68 |
+
- `scripts/smoke_check.py`
|
| 69 |
+
- `DEPLOYMENT.md`
|
| 70 |
+
|
| 71 |
+
## Files to Exclude
|
| 72 |
+
|
| 73 |
+
Do not deploy local-only or sensitive files:
|
| 74 |
+
|
| 75 |
+
- `.env`
|
| 76 |
+
- `.env.*`
|
| 77 |
+
- `logs/`
|
| 78 |
+
- `faiss_store/`
|
| 79 |
+
- `__pycache__/`
|
| 80 |
+
- `*.pyc`
|
| 81 |
+
|
| 82 |
+
Usually unnecessary for the Space runtime:
|
| 83 |
+
|
| 84 |
+
- `tests/`
|
| 85 |
+
- `eval/`
|
| 86 |
+
|
| 87 |
+
These exclusions are defined in `.hfignore`.
|
| 88 |
+
|
| 89 |
+
## Runtime Notes
|
| 90 |
+
|
| 91 |
+
- The app requires `OPENAI_API_KEY` at startup.
|
| 92 |
+
- The CSV files in `data/` must exist or `app.py` will fail fast.
|
| 93 |
+
- Logging currently writes to `logs/app.log`, so avoid deploying old local log files.
|
| 94 |
+
- The FAISS index is built from the dataset during app initialization, so local cached index artifacts do not need to be deployed.
|
| 95 |
+
|
| 96 |
+
## Safety and Privacy Checks
|
| 97 |
+
|
| 98 |
+
Before deployment, review:
|
| 99 |
+
|
| 100 |
+
- whether logs contain raw symptom text
|
| 101 |
+
- whether any test-only or debug-only output should be removed
|
| 102 |
+
- whether emergency escalation language is still present for chest pain and breathing trouble
|
| 103 |
+
- whether the README disclaimer matches the current product behavior
|
| 104 |
+
|
| 105 |
+
## Suggested Release Flow
|
| 106 |
+
|
| 107 |
+
1. Run smoke checks.
|
| 108 |
+
2. Run real-query evaluation.
|
| 109 |
+
3. Run tests.
|
| 110 |
+
4. Review `.gitignore`.
|
| 111 |
+
5. Verify Space Secret configuration.
|
| 112 |
+
6. Push to Hugging Face.
|
| 113 |
+
7. Confirm the Space boots successfully and responds to a few sample queries.
|
MakeFile.mak
CHANGED
|
@@ -1,34 +1,28 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
clean:
|
| 30 |
-
rm -rf __pycache__ */__pycache__ .pytest_cache
|
| 31 |
-
|
| 32 |
-
# Reset environment completely
|
| 33 |
-
reset:
|
| 34 |
-
rm -rf $(VENV)
|
|
|
|
| 1 |
+
PYTHON = .venv\Scripts\python.exe
|
| 2 |
+
PIP = .venv\Scripts\pip.exe
|
| 3 |
+
|
| 4 |
+
venv:
|
| 5 |
+
python -m venv .venv
|
| 6 |
+
|
| 7 |
+
install:
|
| 8 |
+
$(PIP) install -r requirements.txt
|
| 9 |
+
|
| 10 |
+
install-dev:
|
| 11 |
+
$(PIP) install -r requirements-dev.txt
|
| 12 |
+
|
| 13 |
+
smoke-check:
|
| 14 |
+
$(PYTHON) scripts\smoke_check.py
|
| 15 |
+
|
| 16 |
+
eval:
|
| 17 |
+
$(PYTHON) scripts\evaluate_real_queries.py
|
| 18 |
+
|
| 19 |
+
test:
|
| 20 |
+
$(PYTHON) -m pytest tests -q
|
| 21 |
+
|
| 22 |
+
run:
|
| 23 |
+
$(PYTHON) app.py
|
| 24 |
+
|
| 25 |
+
deploy-check:
|
| 26 |
+
$(PYTHON) scripts\smoke_check.py
|
| 27 |
+
$(PYTHON) scripts\evaluate_real_queries.py
|
| 28 |
+
$(PYTHON) -m pytest tests -q
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,31 +1,163 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: MediBot
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom: yellow
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 6.6.0
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
<
|
| 20 |
-
|
| 21 |
-
<
|
| 22 |
-
|
| 23 |
-
<
|
| 24 |
-
|
| 25 |
-
<p align="center">
|
| 26 |
-
|
| 27 |
-
</p>
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: MediBot
|
| 3 |
+
emoji: stethoscope
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.6.0
|
| 8 |
+
python_version: 3.12
|
| 9 |
+
app_file: app.py
|
| 10 |
+
pinned: false
|
| 11 |
+
license: mit
|
| 12 |
+
short_description: Educational symptom-checking demo with emergency escalation guidance
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
<p align="center">
|
| 16 |
+
<img src="static/Medibot%20logo.png" width="320" alt="MediBot Logo">
|
| 17 |
+
</p>
|
| 18 |
+
|
| 19 |
+
<h1 align="center">MediBot</h1>
|
| 20 |
+
|
| 21 |
+
<p align="center">
|
| 22 |
+
Educational symptom exploration with Gradio, OpenAI, FAISS, and a lightweight ranking pipeline.
|
| 23 |
+
</p>
|
| 24 |
+
|
| 25 |
+
<p align="center">
|
| 26 |
+
<em>Not a medical device. For educational use only. Do not use this app to rule out emergencies or replace a licensed clinician.</em>
|
| 27 |
+
</p>
|
| 28 |
+
|
| 29 |
+
## Overview
|
| 30 |
+
|
| 31 |
+
MediBot accepts symptom questions in plain language and can:
|
| 32 |
+
|
| 33 |
+
- extract structured symptom context from user text
|
| 34 |
+
- ask follow-up questions when the symptom signal is too weak or ambiguous
|
| 35 |
+
- estimate urgency for recognized symptoms
|
| 36 |
+
- rank possible conditions for educational review
|
| 37 |
+
- explain named conditions and list precautions
|
| 38 |
+
- add travel-aware handling for rare tropical diseases
|
| 39 |
+
|
| 40 |
+
The app is built around a small multi-step workflow in [app.py](app.py):
|
| 41 |
+
|
| 42 |
+
- `ReActRouter` builds a short plan for each turn
|
| 43 |
+
- `ClarificationAgent` decides whether follow-up questions are needed
|
| 44 |
+
- `SymptomSeverityAgent` scores urgency and handles red-flag escalation
|
| 45 |
+
- `DiseaseDiagnosisAgent` maps symptoms, retrieves FAISS candidates, and scores them
|
| 46 |
+
- description and precaution agents answer disease-specific questions
|
| 47 |
+
|
| 48 |
+
## Repository Layout
|
| 49 |
+
|
| 50 |
+
```text
|
| 51 |
+
MediBot/
|
| 52 |
+
|-- app.py
|
| 53 |
+
|-- data/
|
| 54 |
+
|-- diagnosis_engine/
|
| 55 |
+
|-- eval/
|
| 56 |
+
|-- scripts/
|
| 57 |
+
|-- static/
|
| 58 |
+
|-- tests/
|
| 59 |
+
`-- requirements.txt
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Key directories:
|
| 63 |
+
|
| 64 |
+
- `data/`: CSV datasets used by the app
|
| 65 |
+
- `diagnosis_engine/`: FAISS retrieval, scoring, reranking, prevalence priors, and vocabulary mapping
|
| 66 |
+
- `eval/`: deterministic real-query evaluation cases and runner
|
| 67 |
+
- `scripts/`: lightweight local checks such as `smoke_check.py`
|
| 68 |
+
- `tests/`: pytest coverage for helpers, chat flow, and realistic symptom queries
|
| 69 |
+
|
| 70 |
+
## Local Setup
|
| 71 |
+
|
| 72 |
+
1. Create and activate a virtual environment.
|
| 73 |
+
2. Install runtime dependencies from `requirements.txt`.
|
| 74 |
+
3. Install `requirements-dev.txt` as well if you want to run tests locally.
|
| 75 |
+
4. Set `OPENAI_API_KEY` in your environment or a local `.env` file.
|
| 76 |
+
5. Run the smoke check before launching the app.
|
| 77 |
+
|
| 78 |
+
Example:
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
python -m venv .venv
|
| 82 |
+
.venv\Scripts\activate
|
| 83 |
+
pip install -r requirements.txt
|
| 84 |
+
pip install -r requirements-dev.txt
|
| 85 |
+
python scripts/smoke_check.py
|
| 86 |
+
python app.py
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
If you use `make`, the repo also includes `MakeFile.mak` with helper targets for setup, tests, and deployment checks.
|
| 90 |
+
|
| 91 |
+
## Testing
|
| 92 |
+
|
| 93 |
+
Quick checks:
|
| 94 |
+
|
| 95 |
+
```bash
|
| 96 |
+
python scripts/smoke_check.py
|
| 97 |
+
python scripts/evaluate_real_queries.py
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
Pytest:
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
.venv\Scripts\python.exe -m pytest tests -q
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
Make targets:
|
| 107 |
+
|
| 108 |
+
```bash
|
| 109 |
+
make -f MakeFile.mak smoke-check
|
| 110 |
+
make -f MakeFile.mak eval
|
| 111 |
+
make -f MakeFile.mak test
|
| 112 |
+
make -f MakeFile.mak deploy-check
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
The real-query evaluation uses natural-language prompts from `eval/real_symptom_queries.json` and runs them through a deterministic fallback path so results stay stable across test runs.
|
| 116 |
+
|
| 117 |
+
## Hugging Face Deployment
|
| 118 |
+
|
| 119 |
+
Before deploying to Hugging Face Spaces:
|
| 120 |
+
|
| 121 |
+
- set `OPENAI_API_KEY` as a Space Secret
|
| 122 |
+
- run `python scripts/smoke_check.py`
|
| 123 |
+
- optionally run `python scripts/evaluate_real_queries.py`
|
| 124 |
+
- confirm all required CSV files are present in `data/`
|
| 125 |
+
- review logging behavior and avoid storing raw public symptom text
|
| 126 |
+
|
| 127 |
+
Do not commit or deploy local-only files:
|
| 128 |
+
|
| 129 |
+
- `.env`
|
| 130 |
+
- `.env.*`
|
| 131 |
+
- `logs/`
|
| 132 |
+
- `faiss_store/`
|
| 133 |
+
- `__pycache__/`
|
| 134 |
+
- `*.pyc`
|
| 135 |
+
|
| 136 |
+
These exclusions are also tracked in `.hfignore`.
|
| 137 |
+
|
| 138 |
+
Optional to exclude from Spaces if you do not need them there:
|
| 139 |
+
|
| 140 |
+
- `tests/`
|
| 141 |
+
- `eval/`
|
| 142 |
+
|
| 143 |
+
## Notes on Ranking
|
| 144 |
+
|
| 145 |
+
The displayed "match strength" is the candidate `hybrid_score`. It combines:
|
| 146 |
+
|
| 147 |
+
- Jaccard overlap
|
| 148 |
+
- TF-IDF cosine similarity
|
| 149 |
+
- symptom coverage
|
| 150 |
+
- a rarity penalty derived from `diagnosis_engine/prevalence.py`
|
| 151 |
+
|
| 152 |
+
Weak matches are expected for broad symptom sets. The app explicitly warns users when the top score is low and asks follow-up questions when evidence is too ambiguous.
|
| 153 |
+
|
| 154 |
+
## Related Docs
|
| 155 |
+
|
| 156 |
+
- [MediBot_Colab.ipynb](MediBot_Colab.ipynb)
|
| 157 |
+
- [APP_FLOW.md](APP_FLOW.md)
|
| 158 |
+
- [DEPLOYMENT.md](DEPLOYMENT.md)
|
| 159 |
+
- [TRAVEL_PROMPT_FEATURE.md](TRAVEL_PROMPT_FEATURE.md)
|
| 160 |
+
- [TROPICAL_DISEASE_FIX.md](TROPICAL_DISEASE_FIX.md)
|
| 161 |
+
- [RARE_DISEASE_FIX.md](RARE_DISEASE_FIX.md)
|
| 162 |
+
- [RARITY_SIMILARITY_FIX.md](RARITY_SIMILARITY_FIX.md)
|
| 163 |
+
- [CONTRIBUTING.md](CONTRIBUTING.md)
|
TRAVEL_PROMPT_FEATURE.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Travel-Aware Prompting
|
| 2 |
+
|
| 3 |
+
## Summary
|
| 4 |
+
|
| 5 |
+
MediBot adds a travel-aware note when tropical diseases appear in the ranked results. This keeps the app from implying that malaria, dengue, or typhoid are likely in the default U.S.-context use case when the user has not mentioned travel or exposure.
|
| 6 |
+
|
| 7 |
+
## Current Behavior
|
| 8 |
+
|
| 9 |
+
The feature is implemented across these files:
|
| 10 |
+
|
| 11 |
+
- `diagnosis_engine/tropical_diseases.py`
|
| 12 |
+
- `diagnosis_engine/diagnosis_agent.py`
|
| 13 |
+
- `app.py`
|
| 14 |
+
|
| 15 |
+
Current flow:
|
| 16 |
+
|
| 17 |
+
1. `DiseaseDiagnosisAgent` scores and ranks candidate diseases.
|
| 18 |
+
2. It flags whether any reranked results are in the tropical disease set.
|
| 19 |
+
3. The response formatter in `app.py` adds an educational note when tropical diseases are present.
|
| 20 |
+
4. Travel-related context from the conversation can also boost rare tropical candidates when the user mentions travel or mosquito exposure.
|
| 21 |
+
|
| 22 |
+
## Why It Exists
|
| 23 |
+
|
| 24 |
+
Tropical diseases can share symptoms with common respiratory or febrile illnesses. Without context, they may appear in results even when they are poor real-world matches for a user in the United States. The feature helps the app:
|
| 25 |
+
|
| 26 |
+
- keep travel-acquired conditions from sounding routine
|
| 27 |
+
- preserve educational value without hiding those diseases completely
|
| 28 |
+
- encourage users to mention relevant exposure history
|
| 29 |
+
|
| 30 |
+
## Related Logic
|
| 31 |
+
|
| 32 |
+
- structured context extraction in `app.py` captures travel and mosquito exposure
|
| 33 |
+
- `score_candidates()` in `diagnosis_engine/scoring.py` applies travel-sensitive adjustments
|
| 34 |
+
- prevalence priors in `diagnosis_engine/prevalence.py` keep tropical diseases low by default
|
| 35 |
+
|
| 36 |
+
## User-Facing Effect
|
| 37 |
+
|
| 38 |
+
When tropical diseases appear in the ranked list, the diagnosis answer includes a note explaining that those conditions are typically linked to travel and are less likely without recent travel or similar exposure.
|
app.py
CHANGED
|
@@ -1,523 +1,1487 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
# For data manipulation
|
| 8 |
import os
|
| 9 |
import re
|
| 10 |
import json
|
| 11 |
-
|
| 12 |
-
import
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
from
|
| 18 |
-
from
|
| 19 |
-
from langchain.agents import create_agent
|
| 20 |
-
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, ToolMessage, SystemMessage, FunctionMessage
|
| 21 |
|
| 22 |
-
|
| 23 |
-
from
|
| 24 |
-
# Use FAISS for vector store
|
| 25 |
-
from langchain_community.vectorstores import FAISS
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
load_dotenv()
|
| 35 |
-
os.getenv("OPENAI_API_KEY")
|
| 36 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 37 |
-
|
| 38 |
-
# Expect OPENAI_API_KEY to be set in HF Space secrets
|
| 39 |
if not OPENAI_API_KEY:
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
BASE_DIR = Path(__file__).resolve().parent
|
| 45 |
-
DATA_DIR = BASE_DIR / "data"
|
| 46 |
-
FAISS_PATH = BASE_DIR / "faiss_store"
|
| 47 |
|
| 48 |
-
#
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
SYMPTOM_DESC_PATH = DATA_DIR / "symptom_Description.csv"
|
| 52 |
-
SYMPTOM_PREC_PATH = DATA_DIR / "symptom_precaution.csv"
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
dataset = pd.read_csv(DATASET_PATH)
|
| 63 |
-
# Load the symptom severity data
|
| 64 |
-
symptom_severity = pd.read_csv(SYMPTOM_SEVERITY_PATH)
|
| 65 |
-
# Load the symptom description data
|
| 66 |
-
symptom_desc = pd.read_csv(SYMPTOM_DESC_PATH)
|
| 67 |
-
# Load the symptom precaution data
|
| 68 |
-
symptom_prec = pd.read_csv(SYMPTOM_PREC_PATH)
|
| 69 |
-
|
| 70 |
-
"""# Data cleanup and standardization"""
|
| 71 |
-
|
| 72 |
-
# Canonicalize the symptom data (clean it so it has consistent and compatible formatting)
|
| 73 |
-
def canon_symptom(x: str) -> str:
|
| 74 |
-
# Convert nulls to blanks ("")
|
| 75 |
-
if pd.isna(x):
|
| 76 |
-
return ""
|
| 77 |
-
# Remove spaces and convert to lowercase
|
| 78 |
-
x = str(x).strip().lower()
|
| 79 |
-
# The symptoms may include underscores and some also have spaces (i.e. "_ "), so replace these with a single space
|
| 80 |
-
x = re.sub(r"\s*_\s*", " ", x)
|
| 81 |
-
# Replace multiple spaces with a single space
|
| 82 |
-
x = re.sub(r" +", " ", x)
|
| 83 |
-
return x
|
| 84 |
-
|
| 85 |
-
# Generic text canonicalization (for disease names, descriptions, and precautions)
|
| 86 |
-
def canon_text(x: str) -> str:
|
| 87 |
-
# Convert nulls to blanks ("")
|
| 88 |
-
if pd.isna(x):
|
| 89 |
-
return ""
|
| 90 |
-
# Strip spaces
|
| 91 |
-
return str(x).strip()
|
| 92 |
-
|
| 93 |
-
"""## Format the disease and symptom data"""
|
| 94 |
-
|
| 95 |
-
# Create a list of all symptom columns
|
| 96 |
-
symp_cols = [c for c in dataset.columns if c.lower().startswith("symptom_")]
|
| 97 |
-
|
| 98 |
-
# Convert the dataset to a long format with "Disease" and "symptom" columns
|
| 99 |
-
long = (
|
| 100 |
-
dataset.melt(id_vars=["Disease"], value_vars=symp_cols, value_name="symptom").drop(columns=["variable"])
|
| 101 |
)
|
| 102 |
|
| 103 |
-
#
|
| 104 |
-
|
| 105 |
-
#
|
| 106 |
-
|
| 107 |
-
#
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
#
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
for disease, symp in disease_to_symptoms.items():
|
| 157 |
-
# Find the intersection of user symptoms w/symptoms for the current disease
|
| 158 |
-
inter = clean_symp.intersection(symp)
|
| 159 |
-
# If we didn't find matching symptoms, this is not a good candidate
|
| 160 |
-
if not inter:
|
| 161 |
-
continue
|
| 162 |
-
# The numerator should be the sum of symptom weights for matching symptoms
|
| 163 |
-
numerator = sum(symptom_to_weight.get(s, 0) for s in inter)
|
| 164 |
-
candidate_score = numerator / denominator
|
| 165 |
-
# Add the candidate disease, score, and sorted maching symptom list
|
| 166 |
-
candidate_list.append((disease, candidate_score, sorted(inter)))
|
| 167 |
-
|
| 168 |
-
# Sort the list in descending order (highest scored first)
|
| 169 |
-
candidate_list.sort(key=lambda x: x[1], reverse=True)
|
| 170 |
-
# Return the top K candidates by score
|
| 171 |
-
return candidate_list[:top_k]
|
| 172 |
-
|
| 173 |
-
# Get a report of severity based on symptoms
|
| 174 |
-
def severity_report(user_symptoms: list[str]):
|
| 175 |
-
# Clean the symptoms and only keep non-blank symptoms
|
| 176 |
-
clean_symp = [canon_symptom(s) for s in user_symptoms]
|
| 177 |
-
clean_symp = [s for s in clean_symp if s]
|
| 178 |
-
|
| 179 |
-
# Get weights per symptom
|
| 180 |
-
weight_per_symp = [(s, symptom_to_weight.get(s, 0)) for s in clean_symp]
|
| 181 |
-
# Get the total weight for all symptoms
|
| 182 |
-
total = sum(w for _, w in weight_per_symp)
|
| 183 |
-
|
| 184 |
-
# Give severity levels based on total symptom weight
|
| 185 |
-
if total <= 5:
|
| 186 |
-
level = "mild"
|
| 187 |
-
elif total <= 12:
|
| 188 |
-
level = "moderate"
|
| 189 |
-
else:
|
| 190 |
-
level = "high"
|
| 191 |
-
|
| 192 |
-
# Track the symptoms that were not found in the severity table (i.e. have no weight)
|
| 193 |
-
no_severity = [s for s in clean_symp if s not in symptom_to_weight]
|
| 194 |
-
|
| 195 |
-
return {
|
| 196 |
-
"Total": total,
|
| 197 |
-
"Level": level,
|
| 198 |
-
"Per symptom": weight_per_symp,
|
| 199 |
-
"Symptoms not in severity table": no_severity
|
| 200 |
-
}
|
| 201 |
-
|
| 202 |
-
# Check data quality
|
| 203 |
-
all_symptoms = set().union(*disease_to_symptoms.values())
|
| 204 |
-
# Get all symptoms w/out a severity weight
|
| 205 |
-
missing_severity = sorted([s for s in all_symptoms if s not in symptom_to_weight])
|
| 206 |
-
|
| 207 |
-
all_diseases = set(disease_to_symptoms.keys())
|
| 208 |
-
# Get diseases missing a description
|
| 209 |
-
missing_desc = sorted([d for d in all_diseases if d not in disease_to_desc])
|
| 210 |
-
# Get diseases missing precautions
|
| 211 |
-
missing_prec = sorted([d for d in all_diseases if d not in disease_to_prec])
|
| 212 |
-
|
| 213 |
-
# Create disease documents
|
| 214 |
-
def disease_doc(disease: str) -> str:
|
| 215 |
-
# Get the symptoms for this disease (from the dataset)
|
| 216 |
-
symptoms = sorted(disease_to_symptoms.get(disease, set()))
|
| 217 |
-
# Get the description for this disease (from the dataset)
|
| 218 |
-
description = disease_to_desc.get(disease, "")
|
| 219 |
-
# Get the precaustions for this disease (from the dataset)
|
| 220 |
-
precautions = disease_to_prec.get(disease, [])
|
| 221 |
-
|
| 222 |
-
return "\n".join([
|
| 223 |
-
f"Disease: {disease}",
|
| 224 |
-
f"Description: {description}",
|
| 225 |
-
"Symptoms: " + ", ".join(symptoms),
|
| 226 |
-
"Precautions: " + ", ".join(precautions) if precautions else "Precautions: (none listed)"
|
| 227 |
-
])
|
| 228 |
-
|
| 229 |
-
docs: List[Document] = []
|
| 230 |
-
for d in sorted(disease_to_symptoms.keys()):
|
| 231 |
-
docs.append(
|
| 232 |
-
Document(
|
| 233 |
-
page_content = disease_doc(d),
|
| 234 |
-
metadata={"disease": d}
|
| 235 |
-
)
|
| 236 |
-
)
|
| 237 |
-
|
| 238 |
-
# Created embeddings of the disease docs and store in a vector store
|
| 239 |
-
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
|
| 240 |
-
# If we don't have embeddings in cache, create them
|
| 241 |
-
def load_or_create_faiss(docs, faiss_path=FAISS_PATH):
|
| 242 |
-
""" Load FAISS index if it exists, otherwise create it from docs and save it. """
|
| 243 |
-
index_file = os.path.join(faiss_path, "index.faiss")
|
| 244 |
-
store_file = os.path.join(faiss_path, "index.pkl")
|
| 245 |
-
# If FAISS cache exists, load it
|
| 246 |
-
if os.path.exists(index_file) and os.path.exists(store_file):
|
| 247 |
-
print("Loading FAISS index from cache...")
|
| 248 |
-
return FAISS.load_local(faiss_path, embeddings, allow_dangerous_deserialization=True)
|
| 249 |
-
# Otherwise create a new FAISS index
|
| 250 |
-
print("⚙️ Building new FAISS index...")
|
| 251 |
-
vectorstore = FAISS.from_documents(docs, embeddings)
|
| 252 |
-
# Ensure directory exists
|
| 253 |
-
os.makedirs(faiss_path, exist_ok=True)
|
| 254 |
-
# Save to disk
|
| 255 |
-
vectorstore.save_local(faiss_path)
|
| 256 |
-
print("💾 Saved FAISS index to disk.")
|
| 257 |
-
return vectorstore
|
| 258 |
-
|
| 259 |
-
# Create or load the FAISS vector store for the disease documents
|
| 260 |
-
vector_store = load_or_create_faiss(docs, faiss_path=FAISS_PATH)
|
| 261 |
-
|
| 262 |
-
# Define schemas to use for the tools
|
| 263 |
-
|
| 264 |
-
# Define the input schema for each tool using Pydantic BaseModel
|
| 265 |
-
class DiagnoseInput(BaseModel):
|
| 266 |
-
# List of symptoms
|
| 267 |
-
symptoms: List[str] = Field(..., description="List of symptoms the user is experiencing")
|
| 268 |
-
# Top K candidates to return (default to 5, but should be between 1 and 10)
|
| 269 |
-
top_k: int = Field(5, ge=1, le=10, description="Number of candidate diseases to return")
|
| 270 |
-
|
| 271 |
-
class SeverityInput(BaseModel):
|
| 272 |
-
# List of symptoms
|
| 273 |
-
symptoms: List[str] = Field(..., description="List of symptoms the user is experiencing")
|
| 274 |
-
|
| 275 |
-
class DiseaseInfoInput(BaseModel):
|
| 276 |
-
# Disease name
|
| 277 |
-
disease: str = Field(..., description="Disease name (must match name in dataset)")
|
| 278 |
-
|
| 279 |
-
class RetrieveDocsInput(BaseModel):
|
| 280 |
-
# Search query
|
| 281 |
-
query: str = Field(..., description="A search query (i.e. symptoms list or disease name)")
|
| 282 |
-
# Top K docs to retrieve (default to 3, but should be between 1 and 10)
|
| 283 |
-
k: int = Field(3, ge=1, le=10, description="How many disease docs to retrieve")
|
| 284 |
-
|
| 285 |
-
# Tools (using RAG, so they are deterministic)
|
| 286 |
-
|
| 287 |
-
# Create a diagnosic tool, using our schema
|
| 288 |
-
@tool(args_schema=DiagnoseInput)
|
| 289 |
-
def diagnose_diseases(symptoms: List[str], top_k: int=5) -> str:
|
| 290 |
-
"""
|
| 291 |
-
Suggest likely diseases based on matching symptoms (using severity weights) from the dataset.
|
| 292 |
-
Returns a JSON string of ranked candidates.
|
| 293 |
-
"""
|
| 294 |
-
# Get the top K disease diagnoses
|
| 295 |
-
results = disease_candidates(symptoms, top_k=top_k)
|
| 296 |
-
# Return a JSON formatted string from the list
|
| 297 |
-
return json.dumps({"candidates": results}, indent=2)
|
| 298 |
-
|
| 299 |
-
# Create a symptom severity calculation tool, using our schema
|
| 300 |
-
@tool(args_schema=SeverityInput)
|
| 301 |
-
def calc_symptom_severity(symptoms: List[str]) -> str:
|
| 302 |
-
"""
|
| 303 |
-
Calculate a symptom severity score using weights from the Symptom-severity.csv dataset.
|
| 304 |
-
Returns a JSON string with the total score, severity level, and weights per symptom.
|
| 305 |
-
"""
|
| 306 |
-
# Get the symptoms severity summary
|
| 307 |
-
report = severity_report(symptoms)
|
| 308 |
-
# Return a JSON formatted string
|
| 309 |
-
return json.dumps(report, indent=2)
|
| 310 |
-
|
| 311 |
-
# Create a tool to get disease description, using our schema
|
| 312 |
-
@tool(args_schema=DiseaseInfoInput)
|
| 313 |
-
def get_disease_description(disease: str) -> str:
|
| 314 |
-
"""
|
| 315 |
-
Get the description for a disease (from the symptom_Description.csv dataset)
|
| 316 |
-
"""
|
| 317 |
-
# Clean the disease name
|
| 318 |
-
disease = canon_text(disease)
|
| 319 |
-
# Lookup the disease description and return
|
| 320 |
-
return disease_to_desc.get(disease, "")
|
| 321 |
-
|
| 322 |
-
# Create a tool to get disease precaution advice, using our schema
|
| 323 |
-
@tool(args_schema=DiseaseInfoInput)
|
| 324 |
-
def get_precaution_advice(disease: str) -> str:
|
| 325 |
-
"""
|
| 326 |
-
Get precaution steps for a disease (from the symptom_precaution.csv dataset)
|
| 327 |
-
"""
|
| 328 |
-
# Clean the disease name
|
| 329 |
-
disease = canon_text(disease)
|
| 330 |
-
# Lookup the disease precautions and return
|
| 331 |
-
return json.dumps(disease_to_prec.get(disease, []), indent=2)
|
| 332 |
-
|
| 333 |
-
# Create a tool to retrieve disease documents from the vector store, using our schema
|
| 334 |
-
@tool(args_schema=RetrieveDocsInput)
|
| 335 |
-
def retrieve_disease_docs(query: str, k: int = 3):
|
| 336 |
-
"""
|
| 337 |
-
Retrieve disease documents from the vector store for "ground truth" and explanations.
|
| 338 |
-
Returns (serialized_text, retrieved_documents).)
|
| 339 |
-
"""
|
| 340 |
-
# Get K similar docs from the vector store, based on the query
|
| 341 |
-
retrieved = vector_store.similarity_search(query, k=k)
|
| 342 |
-
# Get a serialized string of the top K matching disease docs
|
| 343 |
-
serialized = "\n\n".join(
|
| 344 |
-
f"Source: {doc.metadata}\nContent\n{doc.page_content}"
|
| 345 |
-
for doc in retrieved
|
| 346 |
-
)
|
| 347 |
-
return serialized
|
| 348 |
-
|
| 349 |
-
tools = [
|
| 350 |
-
diagnose_diseases,
|
| 351 |
-
calc_symptom_severity,
|
| 352 |
-
get_disease_description,
|
| 353 |
-
get_precaution_advice,
|
| 354 |
-
retrieve_disease_docs,
|
| 355 |
-
]
|
| 356 |
|
| 357 |
-
|
| 358 |
|
| 359 |
-
#
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
api_key=OPENAI_API_KEY,
|
| 365 |
-
)
|
| 366 |
-
system_prompt = """
|
| 367 |
-
You are a medical decision support assistant, not to be used as a replacement for professional medical care.
|
| 368 |
-
In your responses, always:
|
| 369 |
-
- Use tools to identify diagnosis candidates and symptom severity
|
| 370 |
-
- Provide a disclaimer that the user should consult with a doctor
|
| 371 |
-
- Give precaution advice and recommend professional medical care when appropriate (i.e. moderate to severe symptoms)
|
| 372 |
-
- If symptoms suggest a serious emergency risk (e.g. chest pain, difficulty breathing, serious bleeding), then recommend urgent care or emergency room services
|
| 373 |
-
|
| 374 |
-
Workflow to follow:
|
| 375 |
-
1) Ask for symptoms if not provided by user
|
| 376 |
-
2) Call calc_symptom_severity(symptoms)
|
| 377 |
-
3) Call diagnose_diseases(symptoms, top_k=5)
|
| 378 |
-
4) For the top 1-3 diseases, call retreive_disease_docs using the disease name or symptoms.
|
| 379 |
-
5) Return: top candidates also with why (matched symptoms), severity level, description + precautions for the top candidate(s), and provide follow-up questions to refine.
|
| 380 |
-
|
| 381 |
-
Responses should always be concise.
|
| 382 |
-
""".strip()
|
| 383 |
-
|
| 384 |
-
agent = create_agent(model, tools, system_prompt=system_prompt)
|
| 385 |
-
|
| 386 |
-
# Multi-turn chat
|
| 387 |
-
def chat_once(messages: List[BaseMessage]) -> List[BaseMessage]:
|
| 388 |
-
"""
|
| 389 |
-
messages: List of BaseMessage objects for the conversation history.
|
| 390 |
-
Returns updated list of BaseMessage objects with the agent's final response added.
|
| 391 |
-
"""
|
| 392 |
-
final_state = None
|
| 393 |
-
for step in agent.stream({"messages": messages}, stream_mode="values"):
|
| 394 |
-
final_state = step
|
| 395 |
-
|
| 396 |
-
# Return the actual BaseMessage objects from the final state
|
| 397 |
-
return final_state["messages"]
|
| 398 |
-
|
| 399 |
-
# For the Gradio UI, we want to run the agent and get the updated LangChain message history, so we can extract the assistant's final response and also maintain the full conversation state (including tool calls) in the UI.
|
| 400 |
-
def run_agent_once(lc_history: List[BaseMessage]) -> List[BaseMessage]:
|
| 401 |
-
"""
|
| 402 |
-
Runs the agent on the current conversation and returns the updated LangChain message history.
|
| 403 |
-
"""
|
| 404 |
-
final_state = None
|
| 405 |
-
for step in agent.stream({"messages": lc_history}, stream_mode="values"):
|
| 406 |
-
final_state = step
|
| 407 |
-
return final_state["messages"]
|
| 408 |
-
|
| 409 |
-
# Helper function to extract the last assistant response content from the LangChain message history
|
| 410 |
-
def get_last_ai_content(lc_history: List[BaseMessage]) -> str:
|
| 411 |
-
"""
|
| 412 |
-
Extract the last assistant response content from the LangChain message history.
|
| 413 |
-
"""
|
| 414 |
-
for m in reversed(lc_history):
|
| 415 |
-
if isinstance(m, AIMessage):
|
| 416 |
-
return (m.content or "").strip()
|
| 417 |
-
return ""
|
| 418 |
-
|
| 419 |
-
# Gradio UI handlers
|
| 420 |
-
def submit_chat(user_text: str, chat_history: List[dict], lc_state: Optional[List[BaseMessage]]):
|
| 421 |
-
"""
|
| 422 |
-
Gradio handler:
|
| 423 |
-
- user_text: current textbox input
|
| 424 |
-
- chat_history: list of {"role": "...", "content": "..."} used by gr.Chatbot(type="messages")
|
| 425 |
-
- lc_state: LangChain BaseMessage history stored in gr.State
|
| 426 |
-
|
| 427 |
-
Returns:
|
| 428 |
-
- updated chat_history (for UI)
|
| 429 |
-
- cleared textbox
|
| 430 |
-
- updated lc_state
|
| 431 |
-
"""
|
| 432 |
-
user_text = (user_text or "").strip()
|
| 433 |
-
if not user_text:
|
| 434 |
-
return chat_history, "", lc_state
|
| 435 |
-
|
| 436 |
-
if lc_state is None:
|
| 437 |
-
lc_state = []
|
| 438 |
-
|
| 439 |
-
# 1) Add user message to LangChain state
|
| 440 |
-
lc_state.append(HumanMessage(content=user_text))
|
| 441 |
-
|
| 442 |
-
# 2) Run agent, get updated LangChain history (includes tool calls, etc.)
|
| 443 |
-
lc_state = run_agent_once(lc_state)
|
| 444 |
-
|
| 445 |
-
# 3) Extract the assistant’s final natural-language response
|
| 446 |
-
assistant_text = get_last_ai_content(lc_state)
|
| 447 |
-
if not assistant_text:
|
| 448 |
-
assistant_text = "I couldn't generate a response. Please try rephrasing your symptoms."
|
| 449 |
-
|
| 450 |
-
# 4) Update the Gradio chat history (messages format)
|
| 451 |
-
chat_history = chat_history + [
|
| 452 |
-
{"role": "user", "content": user_text},
|
| 453 |
-
{"role": "assistant", "content": assistant_text},
|
| 454 |
-
]
|
| 455 |
|
| 456 |
-
|
|
|
|
|
|
|
|
|
|
| 457 |
|
| 458 |
-
#
|
| 459 |
-
|
| 460 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
|
| 462 |
-
#
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 471 |
|
| 472 |
-
|
| 473 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 481 |
)
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
],
|
| 492 |
-
|
| 493 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
)
|
| 495 |
|
| 496 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
|
| 498 |
-
#
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 506 |
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
|
| 514 |
-
#
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
|
| 521 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
if __name__ == "__main__":
|
| 523 |
-
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
medical_chatbot_app.py
|
| 3 |
+
|
| 4 |
+
Multi-agent medical assistant with:
|
| 5 |
+
- ReAct-style LLM router
|
| 6 |
+
- FAISS-based diagnosis engine (in diagnosis_engine)
|
| 7 |
+
- Symptom severity scoring
|
| 8 |
+
- Disease description + precautions
|
| 9 |
+
- Logging & usage metrics
|
| 10 |
+
- Gradio UI
|
| 11 |
+
|
| 12 |
+
Requires:
|
| 13 |
+
pip install pandas numpy faiss-cpu scikit-learn gradio openai python-dotenv
|
| 14 |
+
"""
|
| 15 |
|
|
|
|
| 16 |
import os
|
| 17 |
import re
|
| 18 |
import json
|
| 19 |
+
import time
|
| 20 |
+
import logging
|
| 21 |
+
import hashlib
|
| 22 |
+
import html
|
| 23 |
+
from logging.handlers import RotatingFileHandler
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Any, Dict, List, Optional
|
| 26 |
|
| 27 |
+
import gradio as gr
|
| 28 |
+
import pandas as pd
|
| 29 |
+
from dotenv import load_dotenv
|
| 30 |
+
from openai import OpenAI
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
from diagnosis_engine import DiseaseDiagnosisAgent
|
| 33 |
+
from diagnosis_engine.vocabulary import map_to_known_symptoms, normalize_symptom
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
# ---------------------------------------------------------------------
|
| 36 |
+
# Environment
|
| 37 |
+
# ---------------------------------------------------------------------
|
| 38 |
|
| 39 |
+
# Load environment variables from likely .env locations relative to this file
|
| 40 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 41 |
+
ENV_CANDIDATES = [
|
| 42 |
+
BASE_DIR / ".env",
|
| 43 |
+
BASE_DIR.parent / ".env",
|
| 44 |
+
Path.cwd() / ".env",
|
| 45 |
+
]
|
| 46 |
+
for env_path in ENV_CANDIDATES:
|
| 47 |
+
if env_path.exists():
|
| 48 |
+
load_dotenv(env_path, override=False)
|
| 49 |
|
| 50 |
+
# Ensure OPENAI_API_KEY is set in the environment
|
|
|
|
|
|
|
| 51 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
|
|
|
|
|
|
| 52 |
if not OPENAI_API_KEY:
|
| 53 |
+
searched = ", ".join(str(path) for path in ENV_CANDIDATES)
|
| 54 |
+
raise RuntimeError(
|
| 55 |
+
"OPENAI_API_KEY environment variable is not set. "
|
| 56 |
+
f"Add it to your environment or a .env file in one of these locations: {searched}"
|
| 57 |
+
)
|
| 58 |
|
| 59 |
+
# Initialize OpenAI client
|
| 60 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
# ---------------------------------------------------------------------
|
| 63 |
+
# Logging setup
|
| 64 |
+
# ---------------------------------------------------------------------
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
os.makedirs("logs", exist_ok=True)
|
| 67 |
+
# Set up a rotating file handler to keep logs manageable, and also log to console
|
| 68 |
+
handler = RotatingFileHandler("logs/app.log", maxBytes=2_000_000, backupCount=5)
|
| 69 |
+
logging.basicConfig(
|
| 70 |
+
level=logging.INFO,
|
| 71 |
+
format="%(message)s",
|
| 72 |
+
handlers=[handler, logging.StreamHandler()],
|
| 73 |
+
)
|
| 74 |
+
logger = logging.getLogger("medical_chatbot")
|
| 75 |
|
| 76 |
+
|
| 77 |
+
SAFE_ERROR_MESSAGE = (
|
| 78 |
+
"I couldn't complete your request. Please rephrase your symptoms, "
|
| 79 |
+
"ask for severity, or name a condition for description/precautions."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
)
|
| 81 |
|
| 82 |
+
# ---------------------------------------------------------------------
|
| 83 |
+
# Metrics store
|
| 84 |
+
# ---------------------------------------------------------------------
|
| 85 |
+
|
| 86 |
+
# Track the number of calls to each agent and other relevant metrics for monitoring and analysis
|
| 87 |
+
METRICS = {
|
| 88 |
+
"diagnosis_calls": 0,
|
| 89 |
+
"severity_calls": 0,
|
| 90 |
+
"clarification_calls": 0,
|
| 91 |
+
"description_calls": 0,
|
| 92 |
+
"precaution_calls": 0,
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
# ---------------------------------------------------------------------
|
| 96 |
+
# ReAct prompt
|
| 97 |
+
# ---------------------------------------------------------------------
|
| 98 |
+
|
| 99 |
+
PLANNER_PROMPT = """
|
| 100 |
+
You are a medical triage planning assistant. Create a short execution plan using one or more of the available agents.
|
| 101 |
+
|
| 102 |
+
Available agents:
|
| 103 |
+
- clarification_agent -> {"user_symptoms": ["symptom_1", "symptom_2"]}
|
| 104 |
+
- disease_diagnosis -> {"user_symptoms": ["symptom_1", "symptom_2"]}
|
| 105 |
+
- symptom_severity -> {"user_symptoms": ["symptom_1", "symptom_2"]}
|
| 106 |
+
- disease_description -> {"disease": "disease_name"}
|
| 107 |
+
- precaution_advisor -> {"disease": "disease_name"}
|
| 108 |
+
|
| 109 |
+
Return JSON only with this exact schema:
|
| 110 |
+
{
|
| 111 |
+
"thought": "short planning rationale",
|
| 112 |
+
"steps": [
|
| 113 |
+
{
|
| 114 |
+
"agent": "clarification_agent | disease_diagnosis | symptom_severity | disease_description | precaution_advisor",
|
| 115 |
+
"reason": "why this step helps",
|
| 116 |
+
"input": {}
|
| 117 |
+
}
|
| 118 |
+
]
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
Rules:
|
| 122 |
+
- Include 1 to 3 steps.
|
| 123 |
+
- Use clarification_agent when symptoms are vague, too few, contradictory, or likely to need follow-up questions before diagnosis.
|
| 124 |
+
- Use symptom_severity when the user asks about urgency or symptoms sound clinically important.
|
| 125 |
+
- Use disease_diagnosis when the user provides symptoms and wants likely causes.
|
| 126 |
+
- Use disease_description and/or precaution_advisor when the user asks about a specific disease.
|
| 127 |
+
- For symptom-based questions, symptom lists must be arrays of strings.
|
| 128 |
+
- For disease-focused questions, disease must be a string.
|
| 129 |
+
- Never wrap the JSON in markdown fences.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
# ---------------------------------------------------------------------
|
| 133 |
+
# Data loading
|
| 134 |
+
# ---------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
DATA_DIR = BASE_DIR / "data"
|
| 137 |
|
| 138 |
+
# Paths to CSV dataset files
|
| 139 |
+
SYMPTOM_DISEASE_FILE = DATA_DIR / "dataset.csv"
|
| 140 |
+
SEVERITY_FILE = DATA_DIR / "Symptom-severity.csv"
|
| 141 |
+
DESCRIPTION_FILE = DATA_DIR / "symptom_Description.csv"
|
| 142 |
+
PRECAUTION_FILE = DATA_DIR / "symptom_precaution.csv"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
# Verify that all required data files are present before starting the app
|
| 145 |
+
for path in [SYMPTOM_DISEASE_FILE, SEVERITY_FILE, DESCRIPTION_FILE, PRECAUTION_FILE]:
|
| 146 |
+
if not path.exists():
|
| 147 |
+
raise FileNotFoundError(f"Missing required data file: {path}")
|
| 148 |
|
| 149 |
+
# Set a threshold to identify urgent cases based on severity scores
|
| 150 |
+
SEVERITY_URGENT_THRESHOLD = 15
|
| 151 |
+
# Some symptoms should prompt an emergency message regardless of the overall score
|
| 152 |
+
EMERGENCY_SYMPTOMS = {
|
| 153 |
+
"chest_pain",
|
| 154 |
+
"breathlessness",
|
| 155 |
+
"shortness_of_breath",
|
| 156 |
+
}
|
| 157 |
+
# A standard message to show when urgent symptoms are detected
|
| 158 |
+
EMERGENCY_MESSAGE = (
|
| 159 |
+
"Urgent symptoms detected that could be a medical emergency. "
|
| 160 |
+
"Please seek immediate medical care now or call emergency services right away, especially "
|
| 161 |
+
"if symptoms are severe, worsening, or accompanied by sweating, fainting, confusion, or pain "
|
| 162 |
+
"spreading to the arm, back, jaw, or neck."
|
| 163 |
+
)
|
| 164 |
+
# Keywords that may indicate travel-related exposure, which can be relevant for certain diagnoses
|
| 165 |
+
TRAVEL_INDICATORS = [
|
| 166 |
+
"travel",
|
| 167 |
+
"traveled",
|
| 168 |
+
"abroad",
|
| 169 |
+
"trip",
|
| 170 |
+
"vacation",
|
| 171 |
+
"south africa",
|
| 172 |
+
"mosquito",
|
| 173 |
+
"exposure",
|
| 174 |
+
]
|
| 175 |
|
| 176 |
+
# Load the datasets
|
| 177 |
+
def load_datasets() -> Dict[str, pd.DataFrame]:
|
| 178 |
+
df_sd = pd.read_csv(SYMPTOM_DISEASE_FILE)
|
| 179 |
+
df_desc = pd.read_csv(DESCRIPTION_FILE)
|
| 180 |
+
df_prec = pd.read_csv(PRECAUTION_FILE)
|
| 181 |
+
df_sev = pd.read_csv(SEVERITY_FILE)
|
| 182 |
+
|
| 183 |
+
# Do preprocessing
|
| 184 |
+
df_sd["Disease"] = df_sd["Disease"].str.strip().str.lower()
|
| 185 |
+
df_desc["Disease"] = df_desc["Disease"].str.strip().str.lower()
|
| 186 |
+
df_prec["Disease"] = df_prec["Disease"].str.strip().str.lower()
|
| 187 |
+
df_sev["Symptom"] = df_sev["Symptom"].str.strip().str.lower()
|
| 188 |
+
|
| 189 |
+
# Return as a dictionary of DataFrames
|
| 190 |
+
return {
|
| 191 |
+
"symptom_disease": df_sd,
|
| 192 |
+
"description": df_desc,
|
| 193 |
+
"precaution": df_prec,
|
| 194 |
+
"severity": df_sev,
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
# Get a list of symptom columns (use on the symptom-disease dataset)
|
| 198 |
+
def extract_symptom_columns(df: pd.DataFrame) -> List[str]:
|
| 199 |
+
return [c for c in df.columns if c.lower() != "disease"]
|
| 200 |
+
|
| 201 |
+
# Normalize text by stripping whitespace and converting to lowercase, for consistent matching and logging
|
| 202 |
+
def normalize(text: str) -> str:
|
| 203 |
+
return re.sub(r"\s+", " ", text.strip().lower())
|
| 204 |
+
|
| 205 |
+
# Calculate a severity score by summing the weights of the user's symptoms based on the severity dataset
|
| 206 |
+
def severity_score(symptoms: List[str], df_sev: pd.DataFrame) -> int:
|
| 207 |
+
sev_map = dict(zip(df_sev["Symptom"], df_sev["weight"].astype(int)))
|
| 208 |
+
return sum(sev_map.get(s, 0) for s in symptoms)
|
| 209 |
+
|
| 210 |
+
# Redact text by hashing it and recording its length, to allow for logging without storing sensitive information
|
| 211 |
+
def redact_text(value: str) -> Dict[str, Any]:
|
| 212 |
+
normalized = (value or "").strip()
|
| 213 |
+
return {
|
| 214 |
+
"text_sha256": hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:16],
|
| 215 |
+
"length": len(normalized),
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
# Extract a JSON object from text
|
| 219 |
+
def extract_json_object(text: str) -> Optional[Dict[str, Any]]:
|
| 220 |
+
if not text:
|
| 221 |
+
return None
|
| 222 |
+
|
| 223 |
+
# Normalize the text
|
| 224 |
+
stripped = text.strip()
|
| 225 |
+
if stripped.startswith("```"):
|
| 226 |
+
stripped = re.sub(r"^```(?:json)?\s*", "", stripped)
|
| 227 |
+
stripped = re.sub(r"\s*```$", "", stripped)
|
| 228 |
+
|
| 229 |
+
# First try to parse the entire text as JSON
|
| 230 |
+
try:
|
| 231 |
+
parsed = json.loads(stripped)
|
| 232 |
+
return parsed if isinstance(parsed, dict) else None
|
| 233 |
+
except Exception:
|
| 234 |
+
pass
|
| 235 |
+
|
| 236 |
+
# Identify the starting and ending braces of the JSON text
|
| 237 |
+
start = stripped.find("{")
|
| 238 |
+
end = stripped.rfind("}")
|
| 239 |
+
if start == -1 or end == -1 or end <= start:
|
| 240 |
+
return None
|
| 241 |
+
|
| 242 |
+
# Try to parse the substring that looks like JSON
|
| 243 |
+
try:
|
| 244 |
+
parsed = json.loads(stripped[start : end + 1])
|
| 245 |
+
return parsed if isinstance(parsed, dict) else None
|
| 246 |
+
except Exception:
|
| 247 |
+
return None
|
| 248 |
+
|
| 249 |
+
# Extract structured context from user input
|
| 250 |
+
def extract_structured_context(text: str, all_symptoms: List[str]) -> Dict[str, Any]:
|
| 251 |
+
lower = normalize(text)
|
| 252 |
+
context: Dict[str, Any] = {
|
| 253 |
+
"reported_symptoms": [],
|
| 254 |
+
"duration": None,
|
| 255 |
+
"progression": None,
|
| 256 |
+
"exposures": [],
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
# Get potential symptoms from the text by splitting on common delimiters and conjunctions
|
| 260 |
+
symptom_candidates = [
|
| 261 |
+
segment.strip()
|
| 262 |
+
for segment in re.split(r"[,\n]| and | but ", lower)
|
| 263 |
+
if segment.strip()
|
| 264 |
+
]
|
| 265 |
+
mapped = map_to_known_symptoms(symptom_candidates, all_symptoms)
|
| 266 |
+
|
| 267 |
+
# Also scan short n-grams from the whole sentence so symptoms embedded
|
| 268 |
+
# in natural phrasing like "I have fever and cough for 3 days" are captured.
|
| 269 |
+
tokens = re.findall(r"[a-z0-9]+", lower)
|
| 270 |
+
ngrams = []
|
| 271 |
+
for size in (1, 2, 3):
|
| 272 |
+
for idx in range(len(tokens) - size + 1):
|
| 273 |
+
ngrams.append(" ".join(tokens[idx : idx + size]))
|
| 274 |
+
|
| 275 |
+
# Get symptom matches using the ngrams
|
| 276 |
+
phrase_matches = map_to_known_symptoms(ngrams, all_symptoms)
|
| 277 |
+
# Combine and deduplicate symptoms from both matching lists
|
| 278 |
+
if phrase_matches:
|
| 279 |
+
mapped = list(dict.fromkeys(mapped + phrase_matches))
|
| 280 |
+
|
| 281 |
+
if mapped:
|
| 282 |
+
context["reported_symptoms"] = mapped
|
| 283 |
+
|
| 284 |
+
# Extract duration info using regex patterns - this will be used to give extra context to the diagnosis agent
|
| 285 |
+
duration_patterns = [
|
| 286 |
+
r"\bfor (\d+\s+(?:hour|hours|day|days|week|weeks|month|months))\b",
|
| 287 |
+
r"\bsince (yesterday|today|last night|this morning|\d+\s+(?:day|days|week|weeks|month|months)\s+ago)\b",
|
| 288 |
+
r"\bstarted (today|yesterday|last night|\d+\s+(?:hour|hours|day|days|week|weeks)\s+ago)\b",
|
| 289 |
+
]
|
| 290 |
+
# Check each pattern to see if it matches any duration information in the user's input
|
| 291 |
+
for pattern in duration_patterns:
|
| 292 |
+
match = re.search(pattern, lower)
|
| 293 |
+
if match:
|
| 294 |
+
context["duration"] = match.group(1)
|
| 295 |
+
break
|
| 296 |
+
|
| 297 |
+
# Extract symptom progression info - can help the diagnosis agent adjust symptom scores
|
| 298 |
+
progression_map = {
|
| 299 |
+
"worse": "worsening",
|
| 300 |
+
"worsening": "worsening",
|
| 301 |
+
"getting worse": "worsening",
|
| 302 |
+
"better": "improving",
|
| 303 |
+
"improving": "improving",
|
| 304 |
+
"same": "stable",
|
| 305 |
+
"unchanged": "stable",
|
| 306 |
+
"staying the same": "stable",
|
| 307 |
+
}
|
| 308 |
+
for phrase, label in progression_map.items():
|
| 309 |
+
if phrase in lower:
|
| 310 |
+
context["progression"] = label
|
| 311 |
+
break
|
| 312 |
+
|
| 313 |
+
# Extract exposure info based on keywords - helps the diagnosis agent consider rare diseases
|
| 314 |
+
# related to travel or specific exposures
|
| 315 |
+
exposure_keywords = {
|
| 316 |
+
"travel": ["travel", "traveled", "abroad", "trip", "vacation"],
|
| 317 |
+
"mosquito exposure": ["mosquito", "bug bites", "insect bites"],
|
| 318 |
+
"sick contacts": ["sick contact", "someone sick", "around sick people", "coworker was sick"],
|
| 319 |
+
"food exposure": ["new food", "undercooked", "restaurant", "takeout"],
|
| 320 |
+
"medication exposure": ["new medication", "started a medication", "antibiotic", "medicine"],
|
| 321 |
+
}
|
| 322 |
+
exposures = []
|
| 323 |
+
for label, keywords in exposure_keywords.items():
|
| 324 |
+
if any(keyword in lower for keyword in keywords):
|
| 325 |
+
exposures.append(label)
|
| 326 |
+
context["exposures"] = exposures
|
| 327 |
+
|
| 328 |
+
return context
|
| 329 |
+
|
| 330 |
+
# Merge structured context from multiple turns, give precedence to new info, but preserving all reported symptoms and exposure info
|
| 331 |
+
def merge_structured_context(existing: Optional[Dict[str, Any]], new: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
| 332 |
+
existing = existing or {}
|
| 333 |
+
new = new or {}
|
| 334 |
+
|
| 335 |
+
merged = {
|
| 336 |
+
"reported_symptoms": [],
|
| 337 |
+
"duration": new.get("duration") or existing.get("duration"),
|
| 338 |
+
"progression": new.get("progression") or existing.get("progression"),
|
| 339 |
+
"exposures": [],
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
# Combine and deduplicate symptoms
|
| 343 |
+
seen_symptoms = set()
|
| 344 |
+
for symptom in existing.get("reported_symptoms", []) + new.get("reported_symptoms", []):
|
| 345 |
+
if symptom not in seen_symptoms:
|
| 346 |
+
merged["reported_symptoms"].append(symptom)
|
| 347 |
+
seen_symptoms.add(symptom)
|
| 348 |
+
|
| 349 |
+
# Combine and deduplicate exposures
|
| 350 |
+
seen_exposures = set()
|
| 351 |
+
for exposure in existing.get("exposures", []) + new.get("exposures", []):
|
| 352 |
+
if exposure not in seen_exposures:
|
| 353 |
+
merged["exposures"].append(exposure)
|
| 354 |
+
seen_exposures.add(exposure)
|
| 355 |
+
|
| 356 |
+
return merged
|
| 357 |
+
|
| 358 |
+
# Format the structured context into a human-readable string to include in the LLM prompt
|
| 359 |
+
def format_structured_context_for_prompt(structured_context: Optional[Dict[str, Any]]) -> str:
|
| 360 |
+
context = structured_context or {}
|
| 361 |
+
lines = []
|
| 362 |
+
|
| 363 |
+
symptoms = context.get("reported_symptoms", [])
|
| 364 |
+
if symptoms:
|
| 365 |
+
lines.append("Known symptoms from prior turns: " + ", ".join(symptoms))
|
| 366 |
+
if context.get("duration"):
|
| 367 |
+
lines.append(f"Symptom duration: {context['duration']}")
|
| 368 |
+
if context.get("progression"):
|
| 369 |
+
lines.append(f"Symptom progression: {context['progression']}")
|
| 370 |
+
if context.get("exposures"):
|
| 371 |
+
lines.append("Relevant exposures: " + ", ".join(context["exposures"]))
|
| 372 |
+
|
| 373 |
+
return "\n".join(lines)
|
| 374 |
+
|
| 375 |
+
# ---------------------------------------------------------------------
|
| 376 |
+
# Agents
|
| 377 |
+
# ---------------------------------------------------------------------
|
| 378 |
+
|
| 379 |
+
# Symptom severity agent
|
| 380 |
+
class SymptomSeverityAgent:
|
| 381 |
+
name = "symptom_severity"
|
| 382 |
+
|
| 383 |
+
def __init__(self, df_sev: pd.DataFrame):
|
| 384 |
+
self.df = df_sev
|
| 385 |
+
|
| 386 |
+
def handle(self, user_symptoms: List[str], **kwargs) -> Dict[str, Any]:
|
| 387 |
+
# Increment the severity_calls metric each time this agent is invoked
|
| 388 |
+
METRICS["severity_calls"] += 1
|
| 389 |
+
# Calculate the severity score based on the user's symptoms and the severity dataset
|
| 390 |
+
score = severity_score(user_symptoms, self.df)
|
| 391 |
+
# Check for any red-flag symptoms that would indicate an urgent situation regardless of the overall score
|
| 392 |
+
matched_red_flags = sorted(set(user_symptoms).intersection(EMERGENCY_SYMPTOMS))
|
| 393 |
+
# Determine urgency based on the severity score and presence of red-flag symptoms
|
| 394 |
+
urgency = "urgent" if matched_red_flags or score >= SEVERITY_URGENT_THRESHOLD else "non-urgent"
|
| 395 |
+
return {
|
| 396 |
+
"severity_score": score,
|
| 397 |
+
"urgency": urgency,
|
| 398 |
+
"matched_red_flags": matched_red_flags,
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
# Clarification agent that asks follow-up questions when needed to improve diagnosis accuracy
|
| 402 |
+
class ClarificationAgent:
|
| 403 |
+
name = "clarification_agent"
|
| 404 |
+
|
| 405 |
+
# The clarification agent uses the diagnosis agent
|
| 406 |
+
def __init__(
|
| 407 |
+
self,
|
| 408 |
+
diagnosis_agent: DiseaseDiagnosisAgent,
|
| 409 |
+
symptom_df: pd.DataFrame,
|
| 410 |
+
symptom_cols: List[str],
|
| 411 |
+
):
|
| 412 |
+
self.diagnosis_agent = diagnosis_agent
|
| 413 |
+
self.df = symptom_df
|
| 414 |
+
self.symptom_cols = symptom_cols
|
| 415 |
+
|
| 416 |
+
# Get the list of symptoms associated with a candidate disease from the dataset
|
| 417 |
+
def _candidate_symptoms(self, disease: str) -> List[str]:
|
| 418 |
+
row = self.df[self.df["Disease"] == normalize(disease)]
|
| 419 |
+
if row.empty:
|
| 420 |
+
return []
|
| 421 |
+
first = row.iloc[0]
|
| 422 |
+
return [
|
| 423 |
+
str(first[col]).strip()
|
| 424 |
+
for col in self.symptom_cols
|
| 425 |
+
if pd.notna(first[col]) and str(first[col]).strip()
|
| 426 |
+
]
|
| 427 |
+
|
| 428 |
+
# Generate follow-up questions based on the top candidate diseases and their associated symptoms
|
| 429 |
+
def _follow_up_questions(
|
| 430 |
+
self,
|
| 431 |
+
user_symptoms: List[str],
|
| 432 |
+
candidates: List[Dict[str, Any]],
|
| 433 |
+
) -> List[str]:
|
| 434 |
+
symptom_set = set(user_symptoms)
|
| 435 |
+
symptom_counts: Dict[str, int] = {}
|
| 436 |
+
for candidate in candidates[:3]:
|
| 437 |
+
for symptom in self._candidate_symptoms(candidate["disease"]):
|
| 438 |
+
if symptom not in symptom_set:
|
| 439 |
+
symptom_counts[symptom] = symptom_counts.get(symptom, 0) + 1
|
| 440 |
+
|
| 441 |
+
ranked = sorted(
|
| 442 |
+
symptom_counts.items(),
|
| 443 |
+
key=lambda item: (item[1], len(item[0]), item[0]),
|
| 444 |
+
reverse=True,
|
| 445 |
+
)
|
| 446 |
|
| 447 |
+
questions = [
|
| 448 |
+
f"Are you also experiencing {symptom.replace('_', ' ')}?"
|
| 449 |
+
for symptom, _ in ranked[:4]
|
| 450 |
+
]
|
| 451 |
+
questions.extend(
|
| 452 |
+
[
|
| 453 |
+
"How long have these symptoms been present?",
|
| 454 |
+
"Have your symptoms been getting worse, staying the same, or improving?",
|
| 455 |
+
"Any recent travel, sick contacts, or new food or medication exposure?",
|
| 456 |
+
]
|
| 457 |
+
)
|
| 458 |
|
| 459 |
+
deduped = []
|
| 460 |
+
seen = set()
|
| 461 |
+
for question in questions:
|
| 462 |
+
if question not in seen:
|
| 463 |
+
deduped.append(question)
|
| 464 |
+
seen.add(question)
|
| 465 |
+
return deduped[:5]
|
| 466 |
+
|
| 467 |
+
# Rerank candidate diseases using the LLM when the initial scores are close or there is uncertainty
|
| 468 |
+
def handle(self, user_symptoms: List[str], **kwargs) -> Dict[str, Any]:
|
| 469 |
+
METRICS["clarification_calls"] += 1
|
| 470 |
+
|
| 471 |
+
# Extract structured context from the user's input to provide additional information to the diagnosis agent
|
| 472 |
+
structured_context = kwargs.get("structured_context") or {}
|
| 473 |
+
# Merge with any existing structured context to preserve information across turns
|
| 474 |
+
result = self.diagnosis_agent.handle(user_symptoms, travel_exposure=kwargs.get("travel_exposure", False))
|
| 475 |
+
candidates = result.get("diagnoses", [])
|
| 476 |
+
|
| 477 |
+
# Set the reason for whether or not clarification is needed
|
| 478 |
+
reason = "enough_signal"
|
| 479 |
+
needs_clarification = False
|
| 480 |
+
# We need at least 2 symptoms
|
| 481 |
+
if len(user_symptoms) < 2:
|
| 482 |
+
needs_clarification = True
|
| 483 |
+
reason = "too_few_symptoms"
|
| 484 |
+
# Check if we have any strong symptom matches
|
| 485 |
+
elif not candidates:
|
| 486 |
+
needs_clarification = True
|
| 487 |
+
reason = "no_strong_matches"
|
| 488 |
+
else:
|
| 489 |
+
# Get the score difference btw the top 2 candidates
|
| 490 |
+
top_score = candidates[0]["hybrid_score"]
|
| 491 |
+
second_score = candidates[1]["hybrid_score"] if len(candidates) > 1 else 0.0
|
| 492 |
+
score_gap = top_score - second_score
|
| 493 |
+
# If the top score is low or the score gap is small, request clarification
|
| 494 |
+
if top_score < 0.25:
|
| 495 |
+
needs_clarification = True
|
| 496 |
+
reason = "weak_match"
|
| 497 |
+
elif score_gap < 0.08:
|
| 498 |
+
needs_clarification = True
|
| 499 |
+
reason = "top_candidates_too_close"
|
| 500 |
+
|
| 501 |
+
# Give the LLM extra context (symptom duration, progression, exposures) to help determine if clarification is needed)
|
| 502 |
+
context_bonus = sum(
|
| 503 |
+
1
|
| 504 |
+
for value in [
|
| 505 |
+
structured_context.get("duration"),
|
| 506 |
+
structured_context.get("progression"),
|
| 507 |
+
bool(structured_context.get("exposures")),
|
| 508 |
+
]
|
| 509 |
+
if value
|
| 510 |
)
|
| 511 |
+
if needs_clarification and context_bonus >= 2 and len(user_symptoms) >= 2 and candidates:
|
| 512 |
+
if candidates[0]["hybrid_score"] >= 0.22:
|
| 513 |
+
needs_clarification = False
|
| 514 |
+
reason = "context_resolved"
|
| 515 |
+
|
| 516 |
+
return {
|
| 517 |
+
"needs_clarification": needs_clarification,
|
| 518 |
+
"reason": reason,
|
| 519 |
+
"questions": self._follow_up_questions(user_symptoms, candidates),
|
| 520 |
+
"candidate_preview": [
|
| 521 |
+
{
|
| 522 |
+
"disease": item["disease"],
|
| 523 |
+
"hybrid_score": item["hybrid_score"],
|
| 524 |
+
}
|
| 525 |
+
for item in candidates[:3]
|
| 526 |
],
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
# Disease description agent
|
| 530 |
+
class DiseaseDescriptionAgent:
|
| 531 |
+
name = "disease_description"
|
| 532 |
+
|
| 533 |
+
def __init__(self, df_desc: pd.DataFrame):
|
| 534 |
+
self.df = df_desc
|
| 535 |
+
|
| 536 |
+
def handle(self, disease: str) -> Dict[str, Any]:
|
| 537 |
+
# Increment the description_calls metric each time this agent is invoked
|
| 538 |
+
METRICS["description_calls"] += 1
|
| 539 |
+
# Look up the disease in the description dataset and return its description, or a default message if not found
|
| 540 |
+
row = self.df[self.df["Disease"] == normalize(disease)]
|
| 541 |
+
if row.empty:
|
| 542 |
+
return {"description": "No description found."}
|
| 543 |
+
return {"description": row["Description"].iloc[0]}
|
| 544 |
+
|
| 545 |
+
# Precaution advisor agent
|
| 546 |
+
class PrecautionAdvisorAgent:
|
| 547 |
+
name = "precaution_advisor"
|
| 548 |
+
|
| 549 |
+
def __init__(self, df_prec: pd.DataFrame):
|
| 550 |
+
self.df = df_prec
|
| 551 |
+
|
| 552 |
+
def handle(self, disease: str) -> Dict[str, Any]:
|
| 553 |
+
# Increment the precaution_calls metric each time this agent is invoked
|
| 554 |
+
METRICS["precaution_calls"] += 1
|
| 555 |
+
# Look up the disease in the precaution dataset and return a list of precautions, or an empty list if not found
|
| 556 |
+
row = self.df[self.df["Disease"] == normalize(disease)]
|
| 557 |
+
if row.empty:
|
| 558 |
+
return {"precautions": []}
|
| 559 |
+
|
| 560 |
+
# Extract all columns that start with "precaution" and have non-empty values, and return them as a list
|
| 561 |
+
first = row.iloc[0]
|
| 562 |
+
precautions = [
|
| 563 |
+
str(first[c]).strip()
|
| 564 |
+
for c in first.index
|
| 565 |
+
if c.lower().startswith("precaution")
|
| 566 |
+
and pd.notna(first[c])
|
| 567 |
+
and str(first[c]).strip()
|
| 568 |
+
]
|
| 569 |
+
return {"precautions": precautions}
|
| 570 |
+
|
| 571 |
+
# ---------------------------------------------------------------------
|
| 572 |
+
# ReAct Router
|
| 573 |
+
# ---------------------------------------------------------------------
|
| 574 |
+
|
| 575 |
+
# The ReActRouter class takes the user's input and conversation history, constructs a prompt for the LLM,
|
| 576 |
+
# and parses the LLM's response to determine which agent to call and with what payload. It also includes logic to handle
|
| 577 |
+
# symptom normalization and mapping, as well as special handling for travel-related symptoms in the diagnosis agent.
|
| 578 |
+
class ReActRouter:
|
| 579 |
+
def __init__(self, agents: Dict[str, Any], all_symptoms: List[str]):
|
| 580 |
+
self.agents = agents
|
| 581 |
+
self.all_symptoms = all_symptoms
|
| 582 |
+
|
| 583 |
+
# Build the messages for the LLM by taking the recent conversation history and appending the user's current input,
|
| 584 |
+
# while ensuring that only relevant roles and content are included.
|
| 585 |
+
def _build_messages(
|
| 586 |
+
self,
|
| 587 |
+
user_input: str,
|
| 588 |
+
history: List[Dict[str, str]],
|
| 589 |
+
structured_context: Optional[Dict[str, Any]] = None,
|
| 590 |
+
) -> List[Dict[str, str]]:
|
| 591 |
+
recent_history = history[-6:] if history else []
|
| 592 |
+
messages = [{"role": "system", "content": PLANNER_PROMPT}]
|
| 593 |
+
context_note = format_structured_context_for_prompt(structured_context)
|
| 594 |
+
if context_note:
|
| 595 |
+
messages.append(
|
| 596 |
+
{
|
| 597 |
+
"role": "system",
|
| 598 |
+
"content": "Structured context from earlier turns:\n" + context_note,
|
| 599 |
+
}
|
| 600 |
+
)
|
| 601 |
+
for item in recent_history:
|
| 602 |
+
role = item.get("role")
|
| 603 |
+
content = item.get("content", "")
|
| 604 |
+
if role in {"user", "assistant"} and content:
|
| 605 |
+
messages.append({"role": role, "content": content})
|
| 606 |
+
messages.append({"role": "user", "content": user_input})
|
| 607 |
+
return messages
|
| 608 |
+
|
| 609 |
+
# Call the LLM to get a plan
|
| 610 |
+
def llm_plan(
|
| 611 |
+
self,
|
| 612 |
+
user_input: str,
|
| 613 |
+
history: List[Dict[str, str]],
|
| 614 |
+
structured_context: Optional[Dict[str, Any]] = None,
|
| 615 |
+
) -> Dict[str, Any]:
|
| 616 |
+
|
| 617 |
+
# Log the input to the router
|
| 618 |
+
resp = client.chat.completions.create(
|
| 619 |
+
model="gpt-4o-mini",
|
| 620 |
+
messages=self._build_messages(user_input, history, structured_context),
|
| 621 |
+
temperature=0,
|
| 622 |
+
)
|
| 623 |
+
text = resp.choices[0].message.content or ""
|
| 624 |
+
|
| 625 |
+
# Log the raw output from the LLM, with redactions
|
| 626 |
+
logger.info(json.dumps({
|
| 627 |
+
"event": "router_llm_output",
|
| 628 |
+
"output_hash": redact_text(text),
|
| 629 |
+
}))
|
| 630 |
+
|
| 631 |
+
parsed = extract_json_object(text)
|
| 632 |
+
if not parsed:
|
| 633 |
+
logger.error(f"Router could not parse structured JSON. Raw output:\n{text}")
|
| 634 |
+
return self._fallback_plan(user_input, structured_context)
|
| 635 |
+
|
| 636 |
+
steps = parsed.get("steps", [])
|
| 637 |
+
if not isinstance(steps, list) or not steps:
|
| 638 |
+
logger.error("Planner steps were missing or invalid.")
|
| 639 |
+
return self._fallback_plan(user_input, structured_context)
|
| 640 |
+
|
| 641 |
+
# Normalize and validate the steps to ensure they conform to the expected schema, and log any issues
|
| 642 |
+
normalized_steps = []
|
| 643 |
+
for step in steps[:3]:
|
| 644 |
+
if not isinstance(step, dict):
|
| 645 |
+
continue
|
| 646 |
+
agent_name = str(step.get("agent", "")).strip()
|
| 647 |
+
payload = step.get("input", {})
|
| 648 |
+
reason = str(step.get("reason", "")).strip()
|
| 649 |
+
if not agent_name or not isinstance(payload, dict):
|
| 650 |
+
continue
|
| 651 |
+
normalized_steps.append(
|
| 652 |
+
{"agent": agent_name, "payload": payload, "reason": reason}
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
if not normalized_steps:
|
| 656 |
+
logger.error("Planner returned no valid steps.")
|
| 657 |
+
return self._fallback_plan(user_input, structured_context)
|
| 658 |
+
|
| 659 |
+
logger.info(json.dumps({
|
| 660 |
+
"event": "planner_parsed",
|
| 661 |
+
"step_count": len(normalized_steps),
|
| 662 |
+
"agents": [step["agent"] for step in normalized_steps],
|
| 663 |
+
}))
|
| 664 |
+
return {"steps": normalized_steps}
|
| 665 |
+
|
| 666 |
+
# If the LLM fails to produce a valid plan, use heuristic rules to create a fallback plan based on symptom keywords and disease mentions
|
| 667 |
+
def _fallback_plan(
|
| 668 |
+
self,
|
| 669 |
+
user_input: str,
|
| 670 |
+
structured_context: Optional[Dict[str, Any]] = None,
|
| 671 |
+
) -> Dict[str, Any]:
|
| 672 |
+
lower = user_input.lower()
|
| 673 |
+
# Split the input into parts, normalize them
|
| 674 |
+
normalized_tokens = [normalize_symptom(part) for part in re.split(r"[,\n]| and ", lower) if part.strip()]
|
| 675 |
+
mapped = map_to_known_symptoms(normalized_tokens, self.all_symptoms)
|
| 676 |
+
structured_context = structured_context or {}
|
| 677 |
+
# If no symptoms were mapped, check the context for previous symptoms from earlier turns
|
| 678 |
+
if not mapped and structured_context.get("reported_symptoms"):
|
| 679 |
+
mapped = structured_context["reported_symptoms"]
|
| 680 |
+
# Look for disease mentions in the input to trigger description or precaution agents
|
| 681 |
+
disease_match = re.search(r"(?:what is|describe|tell me about|precautions for)\s+([a-zA-Z\s\-]+)", lower)
|
| 682 |
+
steps: List[Dict[str, Any]] = []
|
| 683 |
+
|
| 684 |
+
# Check if the user is asking about symptoms urgency or severity
|
| 685 |
+
if any(term in lower for term in ["how urgent", "severity", "serious", "emergency"]):
|
| 686 |
+
# If we have mapped symptoms, call the symptom severity agent to evaluate
|
| 687 |
+
if mapped:
|
| 688 |
+
return {"steps": [{"agent": "symptom_severity", "payload": {"user_symptoms": mapped}, "reason": "Assess clinical urgency."}]}
|
| 689 |
+
return {"error": SAFE_ERROR_MESSAGE}
|
| 690 |
+
|
| 691 |
+
# If we have mapped symptoms, add steps for clarification, severity, and diagnosis agents to the plan
|
| 692 |
+
if mapped:
|
| 693 |
+
steps.append(
|
| 694 |
+
{"agent": "clarification_agent", "payload": {"user_symptoms": mapped}, "reason": "Check whether follow-up questions are needed before diagnosis."}
|
| 695 |
+
)
|
| 696 |
+
steps.append(
|
| 697 |
+
{"agent": "symptom_severity", "payload": {"user_symptoms": mapped}, "reason": "Assess urgency for the same symptom set."}
|
| 698 |
+
)
|
| 699 |
+
steps.append(
|
| 700 |
+
{"agent": "disease_diagnosis", "payload": {"user_symptoms": mapped}, "reason": "Find likely conditions from symptoms if the evidence is specific enough."}
|
| 701 |
+
)
|
| 702 |
+
return {"steps": steps[:3]}
|
| 703 |
+
|
| 704 |
+
if disease_match:
|
| 705 |
+
# Normalize the disease match info
|
| 706 |
+
disease = normalize(disease_match.group(1))
|
| 707 |
+
|
| 708 |
+
# If the user asked about precautions, call the precaution advisor agent
|
| 709 |
+
if "precaution" in lower:
|
| 710 |
+
steps.append(
|
| 711 |
+
{"agent": "precaution_advisor", "payload": {"disease": disease}, "reason": "Provide basic safety guidance."}
|
| 712 |
+
)
|
| 713 |
+
else:
|
| 714 |
+
# Add steps to call the disease description and precaution agents
|
| 715 |
+
steps.append(
|
| 716 |
+
{"agent": "disease_description", "payload": {"disease": disease}, "reason": "Explain the named condition."}
|
| 717 |
+
)
|
| 718 |
+
steps.append(
|
| 719 |
+
{"agent": "precaution_advisor", "payload": {"disease": disease}, "reason": "Provide basic safety guidance."}
|
| 720 |
+
)
|
| 721 |
+
return {"steps": steps}
|
| 722 |
+
|
| 723 |
+
return {"error": SAFE_ERROR_MESSAGE}
|
| 724 |
+
|
| 725 |
+
# The main method for generating a plan to produce a response to user input
|
| 726 |
+
def plan(
|
| 727 |
+
self,
|
| 728 |
+
user_input: str,
|
| 729 |
+
history: List[Dict[str, str]],
|
| 730 |
+
structured_context: Optional[Dict[str, Any]] = None,
|
| 731 |
+
) -> Dict[str, Any]:
|
| 732 |
+
parsed = self.llm_plan(user_input, history, structured_context)
|
| 733 |
+
if "error" in parsed:
|
| 734 |
+
return parsed
|
| 735 |
+
|
| 736 |
+
structured_context = structured_context or {}
|
| 737 |
+
# Set a flag to indicate if the user has mentioned travel or exposure that could make certain diseases more likely
|
| 738 |
+
travel_exposure_flag = (
|
| 739 |
+
any(token in user_input.lower() for token in TRAVEL_INDICATORS)
|
| 740 |
+
or any("travel" in exposure or "mosquito" in exposure for exposure in structured_context.get("exposures", []))
|
| 741 |
+
)
|
| 742 |
+
executable_steps = []
|
| 743 |
+
# Iterate through the steps
|
| 744 |
+
for step in parsed["steps"]:
|
| 745 |
+
agent_name = step["agent"]
|
| 746 |
+
payload = dict(step["payload"])
|
| 747 |
+
if agent_name not in self.agents:
|
| 748 |
+
logger.error(f"Unknown agent in plan: {agent_name}")
|
| 749 |
+
continue
|
| 750 |
+
|
| 751 |
+
# Extract any symptoms in the payload and map to known symptoms
|
| 752 |
+
if "user_symptoms" in payload:
|
| 753 |
+
raw_symptoms = payload["user_symptoms"]
|
| 754 |
+
if not isinstance(raw_symptoms, list):
|
| 755 |
+
continue
|
| 756 |
+
|
| 757 |
+
normalized = [normalize_symptom(s) for s in raw_symptoms]
|
| 758 |
+
mapped = map_to_known_symptoms(normalized, self.all_symptoms)
|
| 759 |
+
logger.info(json.dumps({
|
| 760 |
+
"event": "planner_mapped_symptoms",
|
| 761 |
+
"agent": agent_name,
|
| 762 |
+
"mapped_count": len(mapped),
|
| 763 |
+
}))
|
| 764 |
+
|
| 765 |
+
if not mapped:
|
| 766 |
+
continue
|
| 767 |
+
payload["user_symptoms"] = mapped
|
| 768 |
+
|
| 769 |
+
# Pass in payload data to help with diagnosis and clarification
|
| 770 |
+
if agent_name == "disease_diagnosis":
|
| 771 |
+
payload["travel_exposure"] = travel_exposure_flag
|
| 772 |
+
if agent_name == "clarification_agent":
|
| 773 |
+
payload["structured_context"] = structured_context
|
| 774 |
+
|
| 775 |
+
executable_steps.append(
|
| 776 |
+
{"agent": agent_name, "payload": payload, "reason": step.get("reason", "")}
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
# If no steps were added, return an appropriate message to the user
|
| 780 |
+
if not executable_steps:
|
| 781 |
+
if travel_exposure_flag:
|
| 782 |
+
return {
|
| 783 |
+
"diagnoses": [],
|
| 784 |
+
"message": "It looks like you mentioned travel or exposure but did not describe symptoms. Please specify symptoms such as fever, rash, or cough.",
|
| 785 |
+
}
|
| 786 |
+
return {
|
| 787 |
+
"diagnoses": [],
|
| 788 |
+
"message": "No recognizable symptoms were detected. Please describe your symptoms in more detail, such as fever, headache, or cough.",
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
return {"steps": executable_steps}
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
# ---------------------------------------------------------------------
|
| 795 |
+
# App
|
| 796 |
+
# ---------------------------------------------------------------------
|
| 797 |
+
|
| 798 |
+
# The MedicalChatbotApp class initializes the agents, loads the datasets, and sets up the Gradio interface.
|
| 799 |
+
class MedicalChatbotApp:
|
| 800 |
+
def __init__(self):
|
| 801 |
+
self.client = OpenAI(api_key=OPENAI_API_KEY)
|
| 802 |
+
self.data = load_datasets()
|
| 803 |
+
self.symptom_cols = extract_symptom_columns(self.data["symptom_disease"])
|
| 804 |
+
|
| 805 |
+
# Define the diagnosis agent
|
| 806 |
+
diagnosis_agent = DiseaseDiagnosisAgent(
|
| 807 |
+
df=self.data["symptom_disease"], # Symptom-disease dataset
|
| 808 |
+
client=self.client,
|
| 809 |
+
llm_model="gpt-4o-mini", # Use a smaller model to reduce latency
|
| 810 |
+
top_k_faiss=10, # Pulling top 10 is reasonable given the total disease count of 41 in the dataset
|
| 811 |
)
|
| 812 |
|
| 813 |
+
self.all_symptoms = diagnosis_agent.all_symptoms
|
| 814 |
+
# Create a disease description lookup dict using the description dataset (makes later lookups faster)
|
| 815 |
+
self.disease_description_lookup = {
|
| 816 |
+
row["Disease"]: row["Description"]
|
| 817 |
+
for _, row in self.data["description"].drop_duplicates(subset=["Disease"]).iterrows()
|
| 818 |
+
}
|
| 819 |
+
# Create a disease precaution lookup dict using the precaution dataset (makes later lookups faster)
|
| 820 |
+
self.disease_precaution_lookup = {}
|
| 821 |
+
for _, row in self.data["precaution"].drop_duplicates(subset=["Disease"]).iterrows():
|
| 822 |
+
disease = row["Disease"]
|
| 823 |
+
precautions = [
|
| 824 |
+
str(row[col]).strip()
|
| 825 |
+
for col in row.index
|
| 826 |
+
if col.lower().startswith("precaution")
|
| 827 |
+
and pd.notna(row[col])
|
| 828 |
+
and str(row[col]).strip()
|
| 829 |
+
]
|
| 830 |
+
self.disease_precaution_lookup[disease] = precautions
|
| 831 |
+
# Create a disease symptom lookup dict using the symptom-disease dataset (makes later lookups faster)
|
| 832 |
+
self.disease_symptom_lookup = {}
|
| 833 |
+
for _, row in self.data["symptom_disease"].iterrows():
|
| 834 |
+
disease = row["Disease"]
|
| 835 |
+
self.disease_symptom_lookup[disease] = [
|
| 836 |
+
str(row[col]).strip()
|
| 837 |
+
for col in self.symptom_cols
|
| 838 |
+
if pd.notna(row[col]) and str(row[col]).strip()
|
| 839 |
+
]
|
| 840 |
+
# Initialize the agents and the router
|
| 841 |
+
self.agents = {
|
| 842 |
+
"clarification_agent": ClarificationAgent(
|
| 843 |
+
diagnosis_agent=diagnosis_agent,
|
| 844 |
+
symptom_df=self.data["symptom_disease"],
|
| 845 |
+
symptom_cols=self.symptom_cols,
|
| 846 |
+
),
|
| 847 |
+
"disease_diagnosis": diagnosis_agent,
|
| 848 |
+
"symptom_severity": SymptomSeverityAgent(self.data["severity"]),
|
| 849 |
+
"disease_description": DiseaseDescriptionAgent(self.data["description"]),
|
| 850 |
+
"precaution_advisor": PrecautionAdvisorAgent(self.data["precaution"]),
|
| 851 |
+
}
|
| 852 |
+
self.router = ReActRouter(self.agents, self.all_symptoms)
|
| 853 |
+
|
| 854 |
+
# Build a log payload
|
| 855 |
+
def _build_log_payload(self, user_input: str, routed: Dict[str, Any], latency: int) -> Dict[str, Any]:
|
| 856 |
+
return {
|
| 857 |
+
"timestamp": time.time(),
|
| 858 |
+
"user_input": redact_text(user_input),
|
| 859 |
+
"response_shape": sorted(routed.keys()),
|
| 860 |
+
"routed_agent": routed.get("agent"),
|
| 861 |
+
"planned_agents": [step["agent"] for step in routed.get("steps", [])] if isinstance(routed.get("steps"), list) else None,
|
| 862 |
+
"metrics": {
|
| 863 |
+
"diagnosis_calls": METRICS["diagnosis_calls"],
|
| 864 |
+
"severity_calls": METRICS["severity_calls"],
|
| 865 |
+
"clarification_calls": METRICS["clarification_calls"],
|
| 866 |
+
"description_calls": METRICS["description_calls"],
|
| 867 |
+
"precaution_calls": METRICS["precaution_calls"],
|
| 868 |
+
},
|
| 869 |
+
"latency_ms": latency,
|
| 870 |
+
}
|
| 871 |
+
|
| 872 |
+
# Format the severity assessment answer based on the severity score, urgency level, and any matched
|
| 873 |
+
# red-flag symptoms
|
| 874 |
+
def _format_severity_answer(
|
| 875 |
+
self,
|
| 876 |
+
score: Optional[int],
|
| 877 |
+
urgency: Optional[str],
|
| 878 |
+
matched_red_flags: Optional[List[str]] = None,
|
| 879 |
+
) -> str:
|
| 880 |
+
severity_level = urgency.upper() if isinstance(urgency, str) else urgency
|
| 881 |
+
recommendation = "recommended" if urgency == "urgent" else "not required urgently"
|
| 882 |
+
red_flag_note = ""
|
| 883 |
+
# If red flags were found, generate a note listing the red-flag symptoms
|
| 884 |
+
if matched_red_flags:
|
| 885 |
+
pretty_flags = ", ".join(symptom.replace("_", " ") for symptom in matched_red_flags)
|
| 886 |
+
red_flag_note = f"\nRed-flag symptoms detected: {pretty_flags}."
|
| 887 |
+
return (
|
| 888 |
+
"Clinical urgency assessment:\n"
|
| 889 |
+
f"- Severity score: {score} (threshold: {SEVERITY_URGENT_THRESHOLD})\n"
|
| 890 |
+
f"- Triage level: {severity_level}\n"
|
| 891 |
+
"Based on your symptoms, this indicates that immediate medical attention is "
|
| 892 |
+
f"{recommendation}.{red_flag_note}\n"
|
| 893 |
+
"Please consult a healthcare provider for evaluation and next steps."
|
| 894 |
+
)
|
| 895 |
|
| 896 |
+
# Format the diagnosis answer
|
| 897 |
+
def _format_diagnosis_answer(
|
| 898 |
+
self,
|
| 899 |
+
diagnosis_input: List[str],
|
| 900 |
+
result: Dict[str, Any],
|
| 901 |
+
severity_result: Optional[Dict[str, Any]] = None,
|
| 902 |
+
) -> str:
|
| 903 |
+
if not result.get("diagnoses"):
|
| 904 |
+
return result.get("message", "No recognizable symptoms were detected.")
|
| 905 |
+
|
| 906 |
+
# Get the top hybrid score from the diagnoses
|
| 907 |
+
top_score = result["diagnoses"][0]["hybrid_score"]
|
| 908 |
+
# Set a minimum score threshold to filter the diagnoses (0.10),
|
| 909 |
+
# but ensure that at least one diagnosis is included even if the scores are low
|
| 910 |
+
min_score = max(0.10, 0.5 * top_score)
|
| 911 |
+
filtered_diagnoses = [item for item in result["diagnoses"] if item["hybrid_score"] >= min_score]
|
| 912 |
+
if not filtered_diagnoses:
|
| 913 |
+
filtered_diagnoses = [result["diagnoses"][0]]
|
| 914 |
+
|
| 915 |
+
# Get the result from the symptom severity agent
|
| 916 |
+
severity_result = severity_result or self.agents["symptom_severity"].handle(diagnosis_input)
|
| 917 |
+
text = (
|
| 918 |
+
"## Clinical Summary\n"
|
| 919 |
+
f"- Symptom set: {', '.join(s.replace('_', ' ') for s in diagnosis_input)}\n"
|
| 920 |
+
f"- Severity score: {severity_result['severity_score']} (threshold: {SEVERITY_URGENT_THRESHOLD})\n"
|
| 921 |
+
f"- Triage level: {severity_result['urgency'].upper()}\n\n"
|
| 922 |
+
)
|
| 923 |
|
| 924 |
+
# If the top score is below a certain threshold, include a note that the matches are weak and
|
| 925 |
+
# that additional symptoms could help narrow down the possibilities. This helps set expectations
|
| 926 |
+
# for the user about the confidence of the diagnosis and encourages them to provide more information if possible.
|
| 927 |
+
if top_score < 0.25:
|
| 928 |
+
text += "We found possible matches based on your symptoms, but none are strong matches.\n\n"
|
| 929 |
+
|
| 930 |
+
text += "## Top Matching Conditions\n\n"
|
| 931 |
+
|
| 932 |
+
# For each filtered diagnosis, look up its description and precautions, and also determine which
|
| 933 |
+
# symptoms matched between the user's input and the symptoms associated with that disease in the dataset.
|
| 934 |
+
for rank, item in enumerate(filtered_diagnoses, start=1):
|
| 935 |
+
disease = item["disease"]
|
| 936 |
+
description = self.disease_description_lookup.get(disease, "No description found.")
|
| 937 |
+
precautions_list = self.disease_precaution_lookup.get(disease, [])
|
| 938 |
+
precautions = ", ".join(precautions_list) if precautions_list else "No specific precautions listed."
|
| 939 |
+
|
| 940 |
+
# Look up the symptoms associated with this disease in the symptom-disease dataset,
|
| 941 |
+
# and determine which of those symptoms match the user's input.
|
| 942 |
+
disease_symptoms = self.disease_symptom_lookup.get(disease, [])
|
| 943 |
+
if disease_symptoms:
|
| 944 |
+
matched = set(diagnosis_input).intersection(set(disease_symptoms))
|
| 945 |
+
matched_text = ", ".join(s.replace("_", " ") for s in sorted(matched)) if matched else "No direct matches"
|
| 946 |
+
else:
|
| 947 |
+
matched_text = "No symptom data available"
|
| 948 |
+
|
| 949 |
+
text += f"### {rank}. {disease.title()}\n"
|
| 950 |
+
text += f"- Match strength: {item['hybrid_score']:.2f}\n"
|
| 951 |
+
text += f"- Matched symptoms: {matched_text}\n"
|
| 952 |
+
text += f"- Description: {description}\n"
|
| 953 |
+
text += f"- Precautions: {precautions}\n\n"
|
| 954 |
+
|
| 955 |
+
# Give the user a message based on the urgency of the symptoms
|
| 956 |
+
if severity_result["urgency"] == "urgent":
|
| 957 |
+
text += "Given the urgent severity, please seek immediate medical attention.\n\n"
|
| 958 |
+
else:
|
| 959 |
+
text += "Please consult a healthcare professional for accurate diagnosis and appropriate treatment.\n\n"
|
| 960 |
+
|
| 961 |
+
# Give a special message if the user mentioned travel or exposure
|
| 962 |
+
if result.get("tropical_diseases_present", False):
|
| 963 |
+
text += (
|
| 964 |
+
"**Important Note**: One or more listed conditions are typically linked to international travel. "
|
| 965 |
+
"If you have not traveled recently, those options are much less likely.\n\n"
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
# If the confidence of the matches is low, prompt for more symptoms
|
| 969 |
+
if top_score < 0.25:
|
| 970 |
+
text += (
|
| 971 |
+
"Additional symptoms (i.e. body ache, sore throat, nausea, or shortness of breath) "
|
| 972 |
+
"could help narrow down the possibilities."
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
return text.strip()
|
| 976 |
+
|
| 977 |
+
# Format the clarification questions into a readable format for the user
|
| 978 |
+
def _render_session_summary(
|
| 979 |
+
self,
|
| 980 |
+
symptom_context: List[str],
|
| 981 |
+
last_diagnoses: List[Dict[str, Any]],
|
| 982 |
+
structured_context: Optional[Dict[str, Any]] = None,
|
| 983 |
+
) -> str:
|
| 984 |
+
structured_context = structured_context or {}
|
| 985 |
+
# If there are no symptoms or diagnoses or structured context yet, show a blank, default summary
|
| 986 |
+
if not symptom_context and not last_diagnoses and not format_structured_context_for_prompt(structured_context):
|
| 987 |
+
return (
|
| 988 |
+
"## Session Summary\n"
|
| 989 |
+
"- Symptoms tracked: none yet\n"
|
| 990 |
+
"- Latest matches: none yet\n"
|
| 991 |
+
"- Structured context: none yet"
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
# Format symptoms, diagnoses, and context for presentation to the user
|
| 995 |
+
symptom_text = ", ".join(s.replace("_", " ") for s in symptom_context) if symptom_context else "none yet"
|
| 996 |
+
diagnosis_text = ", ".join(item["disease"].title() for item in last_diagnoses[:3]) if last_diagnoses else "none yet"
|
| 997 |
+
context_parts = []
|
| 998 |
+
if structured_context.get("duration"):
|
| 999 |
+
context_parts.append(f"duration {structured_context['duration']}")
|
| 1000 |
+
if structured_context.get("progression"):
|
| 1001 |
+
context_parts.append(f"progression {structured_context['progression']}")
|
| 1002 |
+
if structured_context.get("exposures"):
|
| 1003 |
+
context_parts.append("exposures " + ", ".join(structured_context["exposures"]))
|
| 1004 |
+
context_text = "; ".join(context_parts) if context_parts else "none yet"
|
| 1005 |
+
return (
|
| 1006 |
+
"## Session Summary\n"
|
| 1007 |
+
f"- Symptoms tracked: {symptom_text}\n"
|
| 1008 |
+
f"- Latest matches: {diagnosis_text}\n"
|
| 1009 |
+
f"- Structured context: {context_text}"
|
| 1010 |
+
)
|
| 1011 |
|
| 1012 |
+
# Render a clinical summary card - this gives a comprehensive overview of the session for the user
|
| 1013 |
+
def _render_result_card(
|
| 1014 |
+
self,
|
| 1015 |
+
symptom_context: List[str],
|
| 1016 |
+
last_diagnoses: List[Dict[str, Any]],
|
| 1017 |
+
severity_result: Optional[Dict[str, Any]],
|
| 1018 |
+
plan_trace: List[Dict[str, str]],
|
| 1019 |
+
clarification_result: Optional[Dict[str, Any]],
|
| 1020 |
+
structured_context: Optional[Dict[str, Any]],
|
| 1021 |
+
) -> str:
|
| 1022 |
+
structured_context = structured_context or {}
|
| 1023 |
+
# Format symptoms for display in the card
|
| 1024 |
+
symptoms_html = "".join(
|
| 1025 |
+
f"<span class='chip'>{html.escape(symptom.replace('_', ' '))}</span>"
|
| 1026 |
+
for symptom in symptom_context[:8]
|
| 1027 |
+
) or "<span class='muted'>No symptoms tracked yet.</span>"
|
| 1028 |
+
# Format severity for disply in the card
|
| 1029 |
+
severity_html = "<span class='muted'>No severity assessment yet.</span>"
|
| 1030 |
+
if severity_result:
|
| 1031 |
+
badge_class = "badge urgent" if severity_result.get("urgency") == "urgent" else "badge nonurgent"
|
| 1032 |
+
severity_html = (
|
| 1033 |
+
f"<div class='{badge_class}'>{html.escape(severity_result.get('urgency', 'unknown').upper())}</div>"
|
| 1034 |
+
f"<p>Severity score: <strong>{severity_result.get('severity_score', 'n/a')}</strong></p>"
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
# Format diseases diagnoses for display in the card
|
| 1038 |
+
diagnosis_items = ""
|
| 1039 |
+
for item in last_diagnoses[:3]:
|
| 1040 |
+
diagnosis_items += (
|
| 1041 |
+
"<div class='result-item'>"
|
| 1042 |
+
f"<div class='result-title'>{html.escape(item['disease'].title())}</div>"
|
| 1043 |
+
f"<div class='result-meta'>Match strength: {item['hybrid_score']:.2f}</div>"
|
| 1044 |
+
"</div>"
|
| 1045 |
+
)
|
| 1046 |
+
if not diagnosis_items:
|
| 1047 |
+
diagnosis_items = "<div class='muted'>No diagnosis results yet.</div>"
|
| 1048 |
+
|
| 1049 |
+
# Format the structured context for display in the card
|
| 1050 |
+
structured_context_html = []
|
| 1051 |
+
if structured_context.get("duration"):
|
| 1052 |
+
structured_context_html.append(f"<div class='result-meta'>Duration: {html.escape(structured_context['duration'])}</div>")
|
| 1053 |
+
if structured_context.get("progression"):
|
| 1054 |
+
structured_context_html.append(f"<div class='result-meta'>Progression: {html.escape(structured_context['progression'])}</div>")
|
| 1055 |
+
if structured_context.get("exposures"):
|
| 1056 |
+
structured_context_html.append(
|
| 1057 |
+
f"<div class='result-meta'>Exposures: {html.escape(', '.join(structured_context['exposures']))}</div>"
|
| 1058 |
+
)
|
| 1059 |
+
context_html = "".join(structured_context_html) or "<div class='muted'>No structured context captured yet.</div>"
|
| 1060 |
+
|
| 1061 |
+
# Format clarification/additional questions for disply in the card
|
| 1062 |
+
clarification_html = "<div class='muted'>No follow-up questions pending.</div>"
|
| 1063 |
+
if clarification_result and clarification_result.get("needs_clarification"):
|
| 1064 |
+
question_items = "".join(
|
| 1065 |
+
f"<li>{html.escape(question)}</li>"
|
| 1066 |
+
for question in clarification_result.get("questions", [])
|
| 1067 |
+
)
|
| 1068 |
+
clarification_html = (
|
| 1069 |
+
f"<div class='result-meta'>Reason: {html.escape(clarification_result.get('reason', 'needs more detail'))}</div>"
|
| 1070 |
+
f"<ul class='plan-list'>{question_items}</ul>"
|
| 1071 |
+
)
|
| 1072 |
+
|
| 1073 |
+
# Format the planner trace for display in the card
|
| 1074 |
+
plan_items = "".join(
|
| 1075 |
+
"<li>"
|
| 1076 |
+
f"<strong>{html.escape(step['agent'])}</strong>: {html.escape(step.get('reason', ''))}"
|
| 1077 |
+
"</li>"
|
| 1078 |
+
for step in plan_trace
|
| 1079 |
+
) or "<li>No planner steps yet.</li>"
|
| 1080 |
+
|
| 1081 |
+
return (
|
| 1082 |
+
"<div class='clinical-card'>"
|
| 1083 |
+
"<div class='card-section'>"
|
| 1084 |
+
"<div class='card-title'>Tracked Symptoms</div>"
|
| 1085 |
+
f"<div class='chip-row'>{symptoms_html}</div>"
|
| 1086 |
+
"</div>"
|
| 1087 |
+
"<div class='card-section'>"
|
| 1088 |
+
"<div class='card-title'>Urgency</div>"
|
| 1089 |
+
f"{severity_html}"
|
| 1090 |
+
"</div>"
|
| 1091 |
+
"<div class='card-section'>"
|
| 1092 |
+
"<div class='card-title'>Top Matches</div>"
|
| 1093 |
+
f"{diagnosis_items}"
|
| 1094 |
+
"</div>"
|
| 1095 |
+
"<div class='card-section'>"
|
| 1096 |
+
"<div class='card-title'>Structured Context</div>"
|
| 1097 |
+
f"{context_html}"
|
| 1098 |
+
"</div>"
|
| 1099 |
+
"<div class='card-section'>"
|
| 1100 |
+
"<div class='card-title'>Follow-Up Questions</div>"
|
| 1101 |
+
f"{clarification_html}"
|
| 1102 |
+
"</div>"
|
| 1103 |
+
"<div class='card-section'>"
|
| 1104 |
+
"<div class='card-title'>Planner Trace</div>"
|
| 1105 |
+
f"<ol class='plan-list'>{plan_items}</ol>"
|
| 1106 |
+
"</div>"
|
| 1107 |
+
"</div>"
|
| 1108 |
+
)
|
| 1109 |
+
|
| 1110 |
+
# Format the emergency answer
|
| 1111 |
+
def _format_emergency_answer(self, matched_red_flags: List[str]) -> str:
|
| 1112 |
+
pretty_flags = ", ".join(symptom.replace("_", " ") for symptom in matched_red_flags)
|
| 1113 |
+
return (
|
| 1114 |
+
f"{EMERGENCY_MESSAGE}\n\n"
|
| 1115 |
+
f"Detected red-flag symptoms: {pretty_flags}.\n"
|
| 1116 |
+
"This app should not be used to rule out serious causes of these symptoms."
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
# Format the clarification answer
|
| 1120 |
+
def _format_clarification_answer(self, clarification_result: Dict[str, Any]) -> str:
|
| 1121 |
+
reason_map = {
|
| 1122 |
+
"too_few_symptoms": "I need a bit more detail before ranking possible conditions.",
|
| 1123 |
+
"no_strong_matches": "Your current symptom list does not map strongly to the dataset yet.",
|
| 1124 |
+
"weak_match": "The current matches are too weak to present confidently.",
|
| 1125 |
+
"top_candidates_too_close": "Several conditions are currently too close to separate confidently.",
|
| 1126 |
+
}
|
| 1127 |
+
intro = reason_map.get(
|
| 1128 |
+
clarification_result.get("reason"),
|
| 1129 |
+
"I need a bit more detail before I can narrow this down reliably.",
|
| 1130 |
+
)
|
| 1131 |
+
questions = clarification_result.get("questions", [])
|
| 1132 |
+
lines = "\n".join(f"- {question}" for question in questions[:5])
|
| 1133 |
+
return (
|
| 1134 |
+
"## Follow-Up Questions\n"
|
| 1135 |
+
f"{intro}\n\n"
|
| 1136 |
+
"Please answer a few of these:\n"
|
| 1137 |
+
f"{lines}\n\n"
|
| 1138 |
+
"Once you answer, I can refine the urgency assessment and possible matches."
|
| 1139 |
+
)
|
| 1140 |
|
| 1141 |
+
# Execute the plan
|
| 1142 |
+
def _execute_plan(
|
| 1143 |
+
self,
|
| 1144 |
+
planned: Dict[str, Any],
|
| 1145 |
+
symptom_context: List[str],
|
| 1146 |
+
structured_context: Optional[Dict[str, Any]] = None,
|
| 1147 |
+
) -> Dict[str, Any]:
|
| 1148 |
+
structured_context = structured_context or {}
|
| 1149 |
+
if "error" in planned:
|
| 1150 |
+
return {"error": planned["error"], "symptom_context": symptom_context, "structured_context": structured_context, "plan_trace": [], "last_diagnoses": [], "severity_result": None}
|
| 1151 |
+
if "diagnoses" in planned and "message" in planned:
|
| 1152 |
+
return {
|
| 1153 |
+
"answer": planned["message"],
|
| 1154 |
+
"symptom_context": symptom_context,
|
| 1155 |
+
"structured_context": structured_context,
|
| 1156 |
+
"plan_trace": [],
|
| 1157 |
+
"last_diagnoses": [],
|
| 1158 |
+
"severity_result": None,
|
| 1159 |
+
}
|
| 1160 |
+
|
| 1161 |
+
diagnosis_result = None
|
| 1162 |
+
severity_result = None
|
| 1163 |
+
clarification_result = None
|
| 1164 |
+
disease_details: Dict[str, Dict[str, Any]] = {}
|
| 1165 |
+
plan_trace: List[Dict[str, str]] = []
|
| 1166 |
+
|
| 1167 |
+
# Iterate through the planned steps
|
| 1168 |
+
for step in planned.get("steps", []):
|
| 1169 |
+
agent_name = step["agent"]
|
| 1170 |
+
payload = dict(step["payload"])
|
| 1171 |
+
plan_trace.append({"agent": agent_name, "reason": step.get("reason", "")})
|
| 1172 |
+
|
| 1173 |
+
if (
|
| 1174 |
+
agent_name == "disease_diagnosis"
|
| 1175 |
+
and clarification_result
|
| 1176 |
+
and clarification_result.get("needs_clarification")
|
| 1177 |
+
):
|
| 1178 |
+
continue
|
| 1179 |
+
|
| 1180 |
+
if agent_name in {"clarification_agent", "disease_diagnosis", "symptom_severity"}:
|
| 1181 |
+
step_symptoms = payload.get("user_symptoms", [])
|
| 1182 |
+
if step_symptoms:
|
| 1183 |
+
symptom_context = sorted(set(symptom_context).union(step_symptoms))
|
| 1184 |
+
payload["user_symptoms"] = symptom_context
|
| 1185 |
+
if agent_name == "disease_diagnosis":
|
| 1186 |
+
payload["structured_context"] = structured_context
|
| 1187 |
+
|
| 1188 |
+
result = self.agents[agent_name].handle(**payload)
|
| 1189 |
+
|
| 1190 |
+
if agent_name == "clarification_agent":
|
| 1191 |
+
clarification_result = result
|
| 1192 |
+
elif agent_name == "disease_diagnosis":
|
| 1193 |
+
diagnosis_result = result
|
| 1194 |
+
elif agent_name == "symptom_severity":
|
| 1195 |
+
severity_result = result
|
| 1196 |
+
else:
|
| 1197 |
+
disease_key = normalize(payload.get("disease", ""))
|
| 1198 |
+
disease_details.setdefault(disease_key, {}).update(result)
|
| 1199 |
+
|
| 1200 |
+
if (
|
| 1201 |
+
agent_name == "symptom_severity"
|
| 1202 |
+
and severity_result
|
| 1203 |
+
and severity_result.get("matched_red_flags")
|
| 1204 |
+
):
|
| 1205 |
+
break
|
| 1206 |
+
|
| 1207 |
+
if severity_result and severity_result.get("matched_red_flags"):
|
| 1208 |
+
return {
|
| 1209 |
+
"answer": self._format_emergency_answer(severity_result["matched_red_flags"]),
|
| 1210 |
+
"symptom_context": symptom_context,
|
| 1211 |
+
"structured_context": structured_context,
|
| 1212 |
+
"plan_trace": plan_trace,
|
| 1213 |
+
"last_diagnoses": [],
|
| 1214 |
+
"severity_result": severity_result,
|
| 1215 |
+
"clarification_result": clarification_result,
|
| 1216 |
+
}
|
| 1217 |
+
|
| 1218 |
+
if clarification_result and clarification_result.get("needs_clarification"):
|
| 1219 |
+
return {
|
| 1220 |
+
"answer": self._format_clarification_answer(clarification_result),
|
| 1221 |
+
"symptom_context": symptom_context,
|
| 1222 |
+
"structured_context": structured_context,
|
| 1223 |
+
"plan_trace": plan_trace,
|
| 1224 |
+
"last_diagnoses": [],
|
| 1225 |
+
"severity_result": severity_result,
|
| 1226 |
+
"clarification_result": clarification_result,
|
| 1227 |
+
}
|
| 1228 |
+
|
| 1229 |
+
if diagnosis_result:
|
| 1230 |
+
answer = self._format_diagnosis_answer(symptom_context, diagnosis_result, severity_result)
|
| 1231 |
+
return {
|
| 1232 |
+
"answer": answer,
|
| 1233 |
+
"symptom_context": symptom_context,
|
| 1234 |
+
"structured_context": structured_context,
|
| 1235 |
+
"plan_trace": plan_trace,
|
| 1236 |
+
"last_diagnoses": diagnosis_result.get("diagnoses", []),
|
| 1237 |
+
"severity_result": severity_result,
|
| 1238 |
+
"clarification_result": clarification_result,
|
| 1239 |
+
}
|
| 1240 |
+
|
| 1241 |
+
if severity_result:
|
| 1242 |
+
answer = self._format_severity_answer(
|
| 1243 |
+
severity_result.get("severity_score"),
|
| 1244 |
+
severity_result.get("urgency"),
|
| 1245 |
+
severity_result.get("matched_red_flags"),
|
| 1246 |
+
)
|
| 1247 |
+
return {
|
| 1248 |
+
"answer": answer,
|
| 1249 |
+
"symptom_context": symptom_context,
|
| 1250 |
+
"structured_context": structured_context,
|
| 1251 |
+
"plan_trace": plan_trace,
|
| 1252 |
+
"last_diagnoses": [],
|
| 1253 |
+
"severity_result": severity_result,
|
| 1254 |
+
"clarification_result": clarification_result,
|
| 1255 |
+
}
|
| 1256 |
+
|
| 1257 |
+
if disease_details:
|
| 1258 |
+
disease_name = next(iter(disease_details))
|
| 1259 |
+
detail = disease_details[disease_name]
|
| 1260 |
+
description = detail.get("description", "No description found.")
|
| 1261 |
+
precautions = detail.get("precautions", [])
|
| 1262 |
+
precaution_text = ", ".join(precautions) if precautions else "No specific precautions listed."
|
| 1263 |
+
answer = (
|
| 1264 |
+
f"## Condition Overview\n"
|
| 1265 |
+
f"- Disease: {disease_name.title()}\n"
|
| 1266 |
+
f"- Description: {description}\n"
|
| 1267 |
+
f"- Precautions: {precaution_text}\n\n"
|
| 1268 |
+
"Please consult a healthcare professional for diagnosis and treatment."
|
| 1269 |
+
)
|
| 1270 |
+
return {
|
| 1271 |
+
"answer": answer,
|
| 1272 |
+
"symptom_context": symptom_context,
|
| 1273 |
+
"structured_context": structured_context,
|
| 1274 |
+
"plan_trace": plan_trace,
|
| 1275 |
+
"last_diagnoses": [],
|
| 1276 |
+
"severity_result": None,
|
| 1277 |
+
"clarification_result": clarification_result,
|
| 1278 |
+
}
|
| 1279 |
+
|
| 1280 |
+
return {
|
| 1281 |
+
"error": SAFE_ERROR_MESSAGE,
|
| 1282 |
+
"symptom_context": symptom_context,
|
| 1283 |
+
"structured_context": structured_context,
|
| 1284 |
+
"plan_trace": plan_trace,
|
| 1285 |
+
"last_diagnoses": [],
|
| 1286 |
+
"severity_result": severity_result,
|
| 1287 |
+
"clarification_result": clarification_result,
|
| 1288 |
+
}
|
| 1289 |
+
|
| 1290 |
+
# The main chat method
|
| 1291 |
+
def chat(self, user_input: str, session_state: Optional[Dict[str, Any]] = None):
|
| 1292 |
+
try:
|
| 1293 |
+
session_state = session_state or {}
|
| 1294 |
+
history = session_state.get("messages", [])
|
| 1295 |
+
symptom_context = session_state.get("symptom_context", [])
|
| 1296 |
+
last_diagnoses = session_state.get("last_diagnoses", [])
|
| 1297 |
+
last_severity = session_state.get("last_severity")
|
| 1298 |
+
last_plan_trace = session_state.get("last_plan_trace", [])
|
| 1299 |
+
last_clarification = session_state.get("last_clarification")
|
| 1300 |
+
structured_context = session_state.get("structured_context", {})
|
| 1301 |
+
|
| 1302 |
+
turn_context = extract_structured_context(user_input, self.all_symptoms)
|
| 1303 |
+
structured_context = merge_structured_context(structured_context, turn_context)
|
| 1304 |
+
if turn_context.get("reported_symptoms"):
|
| 1305 |
+
symptom_context = sorted(set(symptom_context).union(turn_context["reported_symptoms"]))
|
| 1306 |
+
|
| 1307 |
+
# Record the start time
|
| 1308 |
+
start = time.time()
|
| 1309 |
+
planned = self.router.plan(user_input, history, structured_context)
|
| 1310 |
+
latency = int((time.time() - start) * 1000)
|
| 1311 |
+
|
| 1312 |
+
logger.info(json.dumps(self._build_log_payload(user_input, planned, latency)))
|
| 1313 |
+
|
| 1314 |
+
executed = self._execute_plan(planned, symptom_context, structured_context)
|
| 1315 |
+
answer = executed.get("answer") or executed.get("error", SAFE_ERROR_MESSAGE)
|
| 1316 |
+
symptom_context = executed.get("symptom_context", symptom_context)
|
| 1317 |
+
structured_context = executed.get("structured_context", structured_context)
|
| 1318 |
+
last_diagnoses = executed.get("last_diagnoses", last_diagnoses)
|
| 1319 |
+
last_severity = executed.get("severity_result", last_severity)
|
| 1320 |
+
last_plan_trace = executed.get("plan_trace", last_plan_trace)
|
| 1321 |
+
last_clarification = executed.get("clarification_result", last_clarification)
|
| 1322 |
+
|
| 1323 |
+
history = history + [
|
| 1324 |
+
{"role": "user", "content": user_input},
|
| 1325 |
+
{"role": "assistant", "content": answer},
|
| 1326 |
+
]
|
| 1327 |
+
updated_state = {
|
| 1328 |
+
"messages": history,
|
| 1329 |
+
"symptom_context": symptom_context,
|
| 1330 |
+
"last_diagnoses": last_diagnoses,
|
| 1331 |
+
"last_severity": last_severity,
|
| 1332 |
+
"last_plan_trace": last_plan_trace,
|
| 1333 |
+
"last_clarification": last_clarification,
|
| 1334 |
+
"structured_context": structured_context,
|
| 1335 |
+
}
|
| 1336 |
+
summary = self._render_session_summary(symptom_context, last_diagnoses, structured_context)
|
| 1337 |
+
# Get the HTML formatted result card to give a comprehensive overview of the session for the user
|
| 1338 |
+
card_html = self._render_result_card(
|
| 1339 |
+
symptom_context,
|
| 1340 |
+
last_diagnoses,
|
| 1341 |
+
last_severity,
|
| 1342 |
+
last_plan_trace,
|
| 1343 |
+
last_clarification,
|
| 1344 |
+
structured_context,
|
| 1345 |
+
)
|
| 1346 |
+
return history, updated_state, summary, card_html
|
| 1347 |
+
|
| 1348 |
+
# Catch any unexpected exceptions, log the error, and return an error message to the user
|
| 1349 |
+
except Exception as exc:
|
| 1350 |
+
logger.error(f"Error in chat: {exc}")
|
| 1351 |
+
error_msg = (
|
| 1352 |
+
"I hit an internal error while processing that request. "
|
| 1353 |
+
"Please try again with a short symptom list like `fever, cough, fatigue`."
|
| 1354 |
+
)
|
| 1355 |
+
session_state = session_state or {}
|
| 1356 |
+
history = session_state.get("messages", [])
|
| 1357 |
+
history = history + [
|
| 1358 |
+
{"role": "user", "content": user_input},
|
| 1359 |
+
{"role": "assistant", "content": error_msg},
|
| 1360 |
+
]
|
| 1361 |
+
updated_state = {
|
| 1362 |
+
"messages": history,
|
| 1363 |
+
"symptom_context": session_state.get("symptom_context", []),
|
| 1364 |
+
"last_diagnoses": session_state.get("last_diagnoses", []),
|
| 1365 |
+
"last_severity": session_state.get("last_severity"),
|
| 1366 |
+
"last_plan_trace": session_state.get("last_plan_trace", []),
|
| 1367 |
+
"last_clarification": session_state.get("last_clarification"),
|
| 1368 |
+
"structured_context": session_state.get("structured_context", {}),
|
| 1369 |
+
}
|
| 1370 |
+
summary = self._render_session_summary(
|
| 1371 |
+
updated_state["symptom_context"],
|
| 1372 |
+
updated_state["last_diagnoses"],
|
| 1373 |
+
updated_state.get("structured_context", {}),
|
| 1374 |
+
)
|
| 1375 |
+
card_html = self._render_result_card(
|
| 1376 |
+
updated_state["symptom_context"],
|
| 1377 |
+
updated_state["last_diagnoses"],
|
| 1378 |
+
updated_state.get("last_severity"),
|
| 1379 |
+
updated_state.get("last_plan_trace", []),
|
| 1380 |
+
updated_state.get("last_clarification"),
|
| 1381 |
+
updated_state.get("structured_context", {}),
|
| 1382 |
+
)
|
| 1383 |
+
return history, updated_state, summary, card_html
|
| 1384 |
+
|
| 1385 |
+
# Launch the Gradio interface
|
| 1386 |
+
def launch(self):
|
| 1387 |
+
custom_css = """
|
| 1388 |
+
.app-shell {max-width: 1280px; margin: 0 auto;}
|
| 1389 |
+
.hero {padding: 18px 20px; border-radius: 18px; background: linear-gradient(135deg, #f6f1df, #dceef5); border: 1px solid #d9d1b5;}
|
| 1390 |
+
.clinical-card {background: #fffdf7; border: 1px solid #d8d1bf; border-radius: 18px; padding: 18px; box-shadow: 0 10px 30px rgba(60, 52, 33, 0.08);}
|
| 1391 |
+
.card-section {margin-bottom: 16px;}
|
| 1392 |
+
.card-title {font-size: 0.85rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: #7a6440; margin-bottom: 8px;}
|
| 1393 |
+
.chip-row {display: flex; flex-wrap: wrap; gap: 8px;}
|
| 1394 |
+
.chip {display: inline-block; background: #efe6cf; color: #4f4027; padding: 6px 10px; border-radius: 999px; font-size: 0.92rem;}
|
| 1395 |
+
.badge {display: inline-block; padding: 7px 12px; border-radius: 999px; font-weight: 700; margin-bottom: 10px;}
|
| 1396 |
+
.badge.urgent {background: #f6d2c9; color: #8a2410;}
|
| 1397 |
+
.badge.nonurgent {background: #dcefdc; color: #1f6134;}
|
| 1398 |
+
.result-item {padding: 10px 0; border-top: 1px solid #ece4d1;}
|
| 1399 |
+
.result-item:first-child {border-top: 0;}
|
| 1400 |
+
.result-title {font-weight: 700; color: #2d2418;}
|
| 1401 |
+
.result-meta, .muted {color: #6d6559;}
|
| 1402 |
+
.plan-list {margin: 0; padding-left: 18px;}
|
| 1403 |
+
"""
|
| 1404 |
+
|
| 1405 |
+
with gr.Blocks(title="MediBot - Disease & Symptom Assistant") as demo:
|
| 1406 |
+
gr.Markdown(
|
| 1407 |
+
"""
|
| 1408 |
+
<div class="app-shell">
|
| 1409 |
+
<div class="hero">
|
| 1410 |
+
<h1>MediBot - Disease & Symptom Assistant</h1>
|
| 1411 |
+
<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>
|
| 1412 |
+
</div>
|
| 1413 |
+
</div>
|
| 1414 |
+
"""
|
| 1415 |
+
)
|
| 1416 |
+
with gr.Row():
|
| 1417 |
+
with gr.Column(scale=7):
|
| 1418 |
+
chatbot = gr.Chatbot(height=520)
|
| 1419 |
+
user_box = gr.Textbox(
|
| 1420 |
+
label="Tell me your symptoms",
|
| 1421 |
+
placeholder="e.g., fever, headache, chills, fatigue",
|
| 1422 |
+
scale=8,
|
| 1423 |
+
)
|
| 1424 |
+
with gr.Column(scale=5):
|
| 1425 |
+
summary = gr.Markdown(self._render_session_summary([], [], {}))
|
| 1426 |
+
result_card = gr.HTML(self._render_result_card([], [], None, [], None, {}))
|
| 1427 |
+
state = gr.State(
|
| 1428 |
+
{
|
| 1429 |
+
"messages": [],
|
| 1430 |
+
"symptom_context": [],
|
| 1431 |
+
"last_diagnoses": [],
|
| 1432 |
+
"last_severity": None,
|
| 1433 |
+
"last_plan_trace": [],
|
| 1434 |
+
"last_clarification": None,
|
| 1435 |
+
"structured_context": {},
|
| 1436 |
+
}
|
| 1437 |
+
)
|
| 1438 |
+
|
| 1439 |
+
# Handle user input from the chat
|
| 1440 |
+
def respond(msg, st):
|
| 1441 |
+
hist, next_state, summary_text, card_html = self.chat(msg, st)
|
| 1442 |
+
return "", hist, next_state, summary_text, card_html
|
| 1443 |
+
|
| 1444 |
+
# Start a new chat and clear out all session tracking objects
|
| 1445 |
+
def new_chat():
|
| 1446 |
+
empty_state = {
|
| 1447 |
+
"messages": [],
|
| 1448 |
+
"symptom_context": [],
|
| 1449 |
+
"last_diagnoses": [],
|
| 1450 |
+
"last_severity": None,
|
| 1451 |
+
"last_plan_trace": [],
|
| 1452 |
+
"last_clarification": None,
|
| 1453 |
+
"structured_context": {},
|
| 1454 |
+
}
|
| 1455 |
+
return [], empty_state, self._render_session_summary([], [], {}), self._render_result_card([], [], None, [], None, {})
|
| 1456 |
+
|
| 1457 |
+
# Submit the user's input
|
| 1458 |
+
user_box.submit(respond, [user_box, state], [user_box, chatbot, state, summary, result_card])
|
| 1459 |
+
|
| 1460 |
+
send_button = gr.Button("Send")
|
| 1461 |
+
send_button.click(respond, [user_box, state], [user_box, chatbot, state, summary, result_card])
|
| 1462 |
+
|
| 1463 |
+
# Add example buttons for quick testing of different symptom scenarios
|
| 1464 |
+
gr.Examples(
|
| 1465 |
+
examples=[
|
| 1466 |
+
"I have fever, headache, chills, and fatigue. What could it be?",
|
| 1467 |
+
"I also have nausea and joint pain.",
|
| 1468 |
+
"Sore throat, runny nose, mild cough for 2 days.",
|
| 1469 |
+
"Chest pain and shortness of breath.",
|
| 1470 |
+
],
|
| 1471 |
+
inputs=user_box,
|
| 1472 |
+
)
|
| 1473 |
+
|
| 1474 |
+
# Add a button to start a new chat, which clears the conversation history and symptom context
|
| 1475 |
+
new_chat_button = gr.Button("New Chat")
|
| 1476 |
+
new_chat_button.click(new_chat, outputs=[chatbot, state, summary, result_card])
|
| 1477 |
+
|
| 1478 |
+
# Add a disclaimer
|
| 1479 |
+
gr.Markdown(
|
| 1480 |
+
"*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.*"
|
| 1481 |
+
)
|
| 1482 |
+
|
| 1483 |
+
demo.launch(css=custom_css)
|
| 1484 |
+
|
| 1485 |
+
# Run the app
|
| 1486 |
if __name__ == "__main__":
|
| 1487 |
+
MedicalChatbotApp().launch()
|
diagnosis_engine/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Import functions to collapse multiple rows of the same disease into a single row with aggregated symptoms
|
| 2 |
+
from .collapse import collapse_disease_rows
|
| 3 |
+
# Import functions to extract and normalize symptoms from user input
|
| 4 |
+
from .vocabulary import extract_unique_symptoms, normalize_symptom
|
| 5 |
+
# Import functions to build the FAISS index and user vectors for similarity search
|
| 6 |
+
from .faiss_index import build_faiss_index, build_user_vector
|
| 7 |
+
# Import functions to build the TF-IDF matrix and user vector for symptom weighting
|
| 8 |
+
from .tfidf import build_tfidf_matrix, build_user_tfidf_vector
|
| 9 |
+
# Import functions to compute scoring metrics for candidate diseases
|
| 10 |
+
from .scoring import (
|
| 11 |
+
compute_jaccard,
|
| 12 |
+
compute_coverage,
|
| 13 |
+
compute_rarity_penalty,
|
| 14 |
+
compute_hybrid_score,
|
| 15 |
+
score_candidates,
|
| 16 |
+
)
|
| 17 |
+
# Import functions to rerank candidate diseases using an LLM (OpenAI for this app)
|
| 18 |
+
from .reranker import LLMReranker
|
| 19 |
+
# Import functions to get disease prevalence data and identify tropical diseases
|
| 20 |
+
from .prevalence import get_disease_prevalence
|
| 21 |
+
# Import the main diagnosis agent class that orchestrates the entire diagnosis process
|
| 22 |
+
from .tropical_diseases import is_tropical_disease, TROPICAL_DISEASES
|
| 23 |
+
# Import the main diagnosis agent class that orchestrates the entire diagnosis process
|
| 24 |
+
from .diagnosis_agent import DiseaseDiagnosisAgent
|
diagnosis_engine/collapse.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This module contains functions to collapse multiple rows of the same disease into a single row with aggregated symptoms.
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from .vocabulary import normalize_symptom
|
| 5 |
+
|
| 6 |
+
# This function takes a DataFrame with multiple rows per disease and collapses them into a single row per disease
|
| 7 |
+
def collapse_disease_rows(df: pd.DataFrame) -> pd.DataFrame:
|
| 8 |
+
"""
|
| 9 |
+
Collapse multiple rows per condition into a single row
|
| 10 |
+
with the union of all normalized symptoms.
|
| 11 |
+
Also preserve the number of original rows per disease (for rarity scoring).
|
| 12 |
+
"""
|
| 13 |
+
symptom_cols = [c for c in df.columns if c.lower().startswith("symptom")]
|
| 14 |
+
|
| 15 |
+
# Count how many times each disease appears in the original dataset
|
| 16 |
+
counts = (
|
| 17 |
+
df["Disease"]
|
| 18 |
+
.str.strip()
|
| 19 |
+
.str.lower()
|
| 20 |
+
.value_counts()
|
| 21 |
+
.to_dict()
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
collapsed = {}
|
| 25 |
+
|
| 26 |
+
# Iterate through each row and aggregate symptoms for each disease
|
| 27 |
+
for _, row in df.iterrows():
|
| 28 |
+
disease = row["Disease"].strip().lower()
|
| 29 |
+
if disease not in collapsed:
|
| 30 |
+
collapsed[disease] = set()
|
| 31 |
+
|
| 32 |
+
for s in row[symptom_cols]:
|
| 33 |
+
if isinstance(s, str) and s.strip():
|
| 34 |
+
collapsed[disease].add(normalize_symptom(s))
|
| 35 |
+
|
| 36 |
+
records = []
|
| 37 |
+
# Create a new DataFrame with one row per disease, including the count of original rows for rarity scoring
|
| 38 |
+
for disease, symptoms in collapsed.items():
|
| 39 |
+
records.append(
|
| 40 |
+
{
|
| 41 |
+
"Disease": disease,
|
| 42 |
+
"Symptoms": sorted(symptoms),
|
| 43 |
+
"Count": counts.get(disease, 1), # ⭐ critical for rarity penalty
|
| 44 |
+
}
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
return pd.DataFrame(records)
|
diagnosis_engine/diagnosis_agent.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
from openai import OpenAI
|
| 3 |
+
from .vocabulary import normalize_symptom, map_to_known_symptoms
|
| 4 |
+
from .faiss_index import build_faiss_index, build_user_vector
|
| 5 |
+
from .tfidf import build_tfidf_matrix, build_user_tfidf_vector
|
| 6 |
+
from .scoring import score_candidates
|
| 7 |
+
from .reranker import LLMReranker
|
| 8 |
+
from .tropical_diseases import is_tropical_disease
|
| 9 |
+
from .prevalence import get_disease_prevalence
|
| 10 |
+
# Constants for scoring adjustments - tuned based on experimentation
|
| 11 |
+
# Boost for tropical diseases if travel exposure is present, to reflect increased likelihood
|
| 12 |
+
TRAVEL_BOOST_MULTIPLIER = 1.15
|
| 13 |
+
# Threshold for when to trigger LLM reranking - if top candidates are close in score, we want the LLM to help
|
| 14 |
+
RERANK_SCORE_GAP_THRESHOLD = 0.12
|
| 15 |
+
|
| 16 |
+
# The main diagnosis agent class that orchestrates the entire diagnosis process
|
| 17 |
+
class DiseaseDiagnosisAgent:
|
| 18 |
+
def __init__(self, df, client: OpenAI, llm_model: str, top_k_faiss: int = 10):
|
| 19 |
+
(
|
| 20 |
+
self.index,
|
| 21 |
+
self.binary_matrix,
|
| 22 |
+
self.diseases,
|
| 23 |
+
self.all_symptoms,
|
| 24 |
+
self.collapsed_df,
|
| 25 |
+
) = build_faiss_index(df)
|
| 26 |
+
print(">>> USING NEW DIAGNOSIS ENGINE <<<")
|
| 27 |
+
|
| 28 |
+
# Load disease frequency counts
|
| 29 |
+
self.disease_counts = dict(zip(
|
| 30 |
+
self.collapsed_df["Disease"],
|
| 31 |
+
self.collapsed_df["Count"]
|
| 32 |
+
))
|
| 33 |
+
|
| 34 |
+
# Load disease prevalence data to penalize rare diseases in scoring
|
| 35 |
+
self.prevalence_map = {
|
| 36 |
+
disease: get_disease_prevalence(disease)
|
| 37 |
+
for disease in self.collapsed_df["Disease"]
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
# Build TF-IDF matrix for symptom weighting in scoring
|
| 41 |
+
self.vectorizer, self.tfidf_matrix = build_tfidf_matrix(self.collapsed_df)
|
| 42 |
+
self.client = client
|
| 43 |
+
self.reranker = LLMReranker(client, llm_model)
|
| 44 |
+
self.top_k_faiss = top_k_faiss
|
| 45 |
+
|
| 46 |
+
# Determines if we should trigger LLM reranking based on how close the top candidate scores are
|
| 47 |
+
def _should_rerank(self, candidates: List[Dict[str, Any]]) -> bool:
|
| 48 |
+
if len(candidates) <= 1:
|
| 49 |
+
return False
|
| 50 |
+
top_score = candidates[0]["hybrid_score"]
|
| 51 |
+
second_score = candidates[1]["hybrid_score"]
|
| 52 |
+
return (top_score - second_score) <= RERANK_SCORE_GAP_THRESHOLD
|
| 53 |
+
|
| 54 |
+
# The main method to handle a diagnosis request - takes user symptoms, travel exposure, and optional structured context
|
| 55 |
+
def handle(
|
| 56 |
+
self,
|
| 57 |
+
user_symptoms: List[str],
|
| 58 |
+
travel_exposure: bool = False,
|
| 59 |
+
structured_context: Optional[Dict[str, Any]] = None,
|
| 60 |
+
) -> Dict[str, Any]:
|
| 61 |
+
normalized = [normalize_symptom(s) for s in user_symptoms]
|
| 62 |
+
mapped = map_to_known_symptoms(normalized, self.all_symptoms)
|
| 63 |
+
|
| 64 |
+
if not mapped:
|
| 65 |
+
return {
|
| 66 |
+
"diagnoses": [],
|
| 67 |
+
"message": "No recognizable symptoms were detected.",
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
user_bin_vec = build_user_vector(mapped, self.all_symptoms)
|
| 71 |
+
user_tfidf_vec = build_user_tfidf_vector(mapped, self.vectorizer)
|
| 72 |
+
|
| 73 |
+
# Perform FAISS similarity search to get candidate diseases based on symptom overlap
|
| 74 |
+
dists, idxs = self.index.search(user_bin_vec, self.top_k_faiss)
|
| 75 |
+
|
| 76 |
+
# Score candidates using Jaccard similarity, coverage, rarity penalty, and a prevalence adjustment
|
| 77 |
+
candidates = score_candidates(
|
| 78 |
+
user_binary_vec=user_bin_vec,
|
| 79 |
+
user_tfidf_vec=user_tfidf_vec,
|
| 80 |
+
faiss_indices=idxs,
|
| 81 |
+
binary_matrix=self.binary_matrix,
|
| 82 |
+
tfidf_matrix=self.tfidf_matrix,
|
| 83 |
+
diseases=self.diseases,
|
| 84 |
+
disease_counts=self.disease_counts,
|
| 85 |
+
prevalence_map=self.prevalence_map,
|
| 86 |
+
mapped_user_symptoms=mapped,
|
| 87 |
+
max_candidates=self.top_k_faiss,
|
| 88 |
+
top_n=5,
|
| 89 |
+
travel_exposure=travel_exposure,
|
| 90 |
+
structured_context=structured_context,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# Filter candidates to only those with at least 10% symptom coverage so we don't use weak matches
|
| 94 |
+
filtered = [c for c in candidates if c["coverage"] >= 0.10]
|
| 95 |
+
|
| 96 |
+
# If no candidates meet the coverage threshold, return an empty result with a message
|
| 97 |
+
if not filtered:
|
| 98 |
+
return {
|
| 99 |
+
"diagnoses": [],
|
| 100 |
+
"message": "No strong matches found for the given symptoms.",
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
reranked = filtered
|
| 104 |
+
# If the top candidates are close in score, trigger LLM reranking to get a better ranking based on symptom details and disease characteristics
|
| 105 |
+
if self._should_rerank(filtered):
|
| 106 |
+
reranked = self.reranker.rerank(
|
| 107 |
+
user_symptoms=mapped,
|
| 108 |
+
candidates=filtered,
|
| 109 |
+
collapsed_df=self.collapsed_df,
|
| 110 |
+
top_k=5,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Apply a small travel-based boost to tropical candidates if travel exposure is present
|
| 114 |
+
if travel_exposure:
|
| 115 |
+
for diag in reranked:
|
| 116 |
+
if is_tropical_disease(diag["disease"]):
|
| 117 |
+
diag["hybrid_score"] += (1.0 - diag["hybrid_score"]) * (TRAVEL_BOOST_MULTIPLIER - 1.0)
|
| 118 |
+
reranked = sorted(reranked, key=lambda x: x["hybrid_score"], reverse=True)
|
| 119 |
+
|
| 120 |
+
# Check for tropical diseases in results
|
| 121 |
+
tropical_diseases_present = any(
|
| 122 |
+
is_tropical_disease(diag["disease"]) for diag in reranked
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
return {
|
| 126 |
+
"diagnoses": reranked,
|
| 127 |
+
"message": "Ranked candidate conditions based on symptom similarity.",
|
| 128 |
+
"tropical_diseases_present": tropical_diseases_present,
|
| 129 |
+
}
|
diagnosis_engine/faiss_index.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import faiss
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from typing import List, Tuple
|
| 5 |
+
from .collapse import collapse_disease_rows
|
| 6 |
+
from .vocabulary import extract_unique_symptoms
|
| 7 |
+
|
| 8 |
+
# This module contains functions to build a FAISS index for efficient similarity search of diseases based on their symptoms.
|
| 9 |
+
def build_binary_matrix(collapsed_df: pd.DataFrame, all_symptoms: List[str]) -> np.ndarray:
|
| 10 |
+
matrix = []
|
| 11 |
+
# For each disease, create a binary vector indicating the presence of each symptom in the all_symptoms list
|
| 12 |
+
for symptoms in collapsed_df["Symptoms"]:
|
| 13 |
+
vector = [1.0 if s in symptoms else 0.0 for s in all_symptoms]
|
| 14 |
+
matrix.append(vector)
|
| 15 |
+
return np.array(matrix, dtype="float32")
|
| 16 |
+
|
| 17 |
+
# This function builds the FAISS index
|
| 18 |
+
def build_faiss_index(
|
| 19 |
+
df: pd.DataFrame,
|
| 20 |
+
) -> Tuple[faiss.IndexFlatIP, np.ndarray, list[str], list[str], pd.DataFrame]:
|
| 21 |
+
collapsed = collapse_disease_rows(df)
|
| 22 |
+
all_symptoms = extract_unique_symptoms(collapsed)
|
| 23 |
+
matrix = build_binary_matrix(collapsed, all_symptoms)
|
| 24 |
+
|
| 25 |
+
# Normalize vectors for cosine similarity (inner product)
|
| 26 |
+
norms = np.linalg.norm(matrix, axis=1, keepdims=True)
|
| 27 |
+
norms[norms == 0] = 1 # Avoid division by zero
|
| 28 |
+
normalized_matrix = matrix / norms
|
| 29 |
+
|
| 30 |
+
dim = normalized_matrix.shape[1]
|
| 31 |
+
# Use cosine similarity for normalized vectors
|
| 32 |
+
index = faiss.IndexFlatIP(dim)
|
| 33 |
+
index.add(normalized_matrix.astype('float32'))
|
| 34 |
+
|
| 35 |
+
diseases = collapsed["Disease"].tolist()
|
| 36 |
+
|
| 37 |
+
print(
|
| 38 |
+
f"Built FAISS index with {len(diseases)} diseases and {len(all_symptoms)} unique symptoms (cosine similarity)."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
return index, matrix, diseases, all_symptoms, collapsed
|
| 42 |
+
|
| 43 |
+
# This function builds a binary vector for the user's symptoms to query the FAISS index
|
| 44 |
+
def build_user_vector(user_symptoms: list[str], all_symptoms: list[str]) -> np.ndarray:
|
| 45 |
+
normalized = set(user_symptoms)
|
| 46 |
+
vector = np.array([[1.0 if s in normalized else 0.0 for s in all_symptoms]], dtype="float32")
|
| 47 |
+
|
| 48 |
+
# Normalize for cosine similarity
|
| 49 |
+
norm = np.linalg.norm(vector)
|
| 50 |
+
if norm > 0:
|
| 51 |
+
vector = vector / norm
|
| 52 |
+
|
| 53 |
+
return vector
|
diagnosis_engine/prevalence.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Disease prevalence data to help with ranking by the diagnosis engine and to improve accuracy.
|
| 2 |
+
This data should not to be shown to the end user.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Dict, List
|
| 6 |
+
|
| 7 |
+
# To keep the app lightweight, use a single data source for prevalence data (IHME GBD) and only a
|
| 8 |
+
# small number of manually mapped diseases that are relevant to the app's use case and dataset.
|
| 9 |
+
SOURCE_CITATIONS: Dict[str, Dict[str, str]] = {
|
| 10 |
+
"ihme_gbd_2021": {
|
| 11 |
+
"label": "IHME Global Burden of Disease Results Tool",
|
| 12 |
+
"url": "https://www.healthdata.org/data-tools-practices/interactive-visuals/gbd-results",
|
| 13 |
+
},
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
# This dictionary contains prevalence data (cases per 100k) for a small number of diseases, along with the source and notes on mapping decisions.
|
| 17 |
+
# Diseases not in this dictionary will get a default "unknown" prevalence.
|
| 18 |
+
PREVALENCE_METADATA: Dict[str, Dict[str, object]] = {
|
| 19 |
+
"diabetes": {
|
| 20 |
+
"per_100k": 8000,
|
| 21 |
+
"sources": ["ihme_gbd_2021"],
|
| 22 |
+
"note": "GBD-backed ranking prior for diabetes mellitus.",
|
| 23 |
+
},
|
| 24 |
+
"migraine": {
|
| 25 |
+
"per_100k": 12000,
|
| 26 |
+
"sources": ["ihme_gbd_2021"],
|
| 27 |
+
"note": "GBD-backed ranking prior for migraine.",
|
| 28 |
+
},
|
| 29 |
+
"bronchial asthma": {
|
| 30 |
+
"per_100k": 8000,
|
| 31 |
+
"sources": ["ihme_gbd_2021"],
|
| 32 |
+
"note": "GBD-backed ranking prior mapped to asthma.",
|
| 33 |
+
},
|
| 34 |
+
"peptic ulcer diseae": {
|
| 35 |
+
"per_100k": 5000,
|
| 36 |
+
"sources": ["ihme_gbd_2021"],
|
| 37 |
+
"note": "GBD-backed ranking prior mapped to peptic ulcer disease.",
|
| 38 |
+
},
|
| 39 |
+
"hepatitis a": {
|
| 40 |
+
"per_100k": 2000,
|
| 41 |
+
"sources": ["ihme_gbd_2021"],
|
| 42 |
+
"note": "GBD-backed ranking prior mapped to acute hepatitis A.",
|
| 43 |
+
},
|
| 44 |
+
"malaria": {
|
| 45 |
+
"per_100k": 1,
|
| 46 |
+
"sources": ["ihme_gbd_2021"],
|
| 47 |
+
"note": "GBD-backed ranking prior for malaria, kept very low for the app's default U.S.-context behavior.",
|
| 48 |
+
},
|
| 49 |
+
"dengue": {
|
| 50 |
+
"per_100k": 1,
|
| 51 |
+
"sources": ["ihme_gbd_2021"],
|
| 52 |
+
"note": "GBD-backed ranking prior for dengue, kept very low for the app's default U.S.-context behavior.",
|
| 53 |
+
},
|
| 54 |
+
"typhoid": {
|
| 55 |
+
"per_100k": 1,
|
| 56 |
+
"sources": ["ihme_gbd_2021"],
|
| 57 |
+
"note": "GBD-backed ranking prior for typhoid/paratyphoid fever, kept very low for the app's default U.S.-context behavior.",
|
| 58 |
+
},
|
| 59 |
+
"aids": {
|
| 60 |
+
"per_100k": 50,
|
| 61 |
+
"sources": ["ihme_gbd_2021"],
|
| 62 |
+
"note": "GBD-backed ranking prior mapped to HIV/AIDS; kept conservative because the dataset label is specifically 'AIDS'.",
|
| 63 |
+
},
|
| 64 |
+
"tuberculosis": {
|
| 65 |
+
"per_100k": 10,
|
| 66 |
+
"sources": ["ihme_gbd_2021"],
|
| 67 |
+
"note": "GBD-backed ranking prior for tuberculosis, kept low for the app's default U.S.-context behavior.",
|
| 68 |
+
},
|
| 69 |
+
"unknown": {
|
| 70 |
+
"per_100k": 1000,
|
| 71 |
+
"sources": [],
|
| 72 |
+
"note": "Fallback prior for diseases without an explicit entry.",
|
| 73 |
+
},
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
# Map diseases to prevalence values for quick lookup
|
| 77 |
+
DISEASE_PREVALENCE = {
|
| 78 |
+
disease: int(meta["per_100k"])
|
| 79 |
+
for disease, meta in PREVALENCE_METADATA.items()
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
# Get prevalence value for a given disease
|
| 83 |
+
def get_disease_prevalence(disease: str) -> int:
|
| 84 |
+
"""Get the ranking prevalence value for a disease in cases per 100k people."""
|
| 85 |
+
normalized = disease.lower().strip()
|
| 86 |
+
return DISEASE_PREVALENCE.get(normalized, DISEASE_PREVALENCE["unknown"])
|
| 87 |
+
|
| 88 |
+
# Get full prevalence metatdata for a give disease
|
| 89 |
+
def get_disease_prevalence_metadata(disease: str) -> Dict[str, object]:
|
| 90 |
+
"""Return the stored prevalence value and its source citation for a disease."""
|
| 91 |
+
normalized = disease.lower().strip()
|
| 92 |
+
return PREVALENCE_METADATA.get(normalized, PREVALENCE_METADATA["unknown"])
|
| 93 |
+
|
| 94 |
+
# Get citations for prevalence data sources for a given disease
|
| 95 |
+
def get_prevalence_citations(disease: str) -> List[Dict[str, str]]:
|
| 96 |
+
"""Resolve source ids into human-readable citation records."""
|
| 97 |
+
metadata = get_disease_prevalence_metadata(disease)
|
| 98 |
+
sources = metadata.get("sources", [])
|
| 99 |
+
return [
|
| 100 |
+
SOURCE_CITATIONS[source_id]
|
| 101 |
+
for source_id in sources
|
| 102 |
+
if source_id in SOURCE_CITATIONS
|
| 103 |
+
]
|
diagnosis_engine/reranker.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Dict, Any
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
|
| 6 |
+
# This class uses an LLM (OpenAI) to rerank candidate diseases based on their symptoms and scores
|
| 7 |
+
class LLMReranker:
|
| 8 |
+
"""
|
| 9 |
+
Deterministic reranker: reorders existing candidates only.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, client: OpenAI, model: str):
|
| 13 |
+
self.client = client
|
| 14 |
+
self.model = model
|
| 15 |
+
|
| 16 |
+
# Rerank candidates using the LLM. Does not add new diseases.
|
| 17 |
+
def rerank(
|
| 18 |
+
self,
|
| 19 |
+
user_symptoms: List[str],
|
| 20 |
+
candidates: List[Dict[str, Any]],
|
| 21 |
+
collapsed_df,
|
| 22 |
+
top_k: int = 5,
|
| 23 |
+
) -> List[Dict[str, Any]]:
|
| 24 |
+
"""
|
| 25 |
+
Rerank candidates using the LLM. Does not add new diseases.
|
| 26 |
+
"""
|
| 27 |
+
# Build a compact description for each candidate
|
| 28 |
+
enriched = []
|
| 29 |
+
for c in candidates:
|
| 30 |
+
idx = c["index"]
|
| 31 |
+
symptoms = collapsed_df.iloc[idx]["Symptoms"]
|
| 32 |
+
enriched.append(
|
| 33 |
+
{
|
| 34 |
+
"disease": c["disease"],
|
| 35 |
+
# Use various scoring metrics to improve accuracy
|
| 36 |
+
"scores": {
|
| 37 |
+
"hybrid_score": c["hybrid_score"],
|
| 38 |
+
"jaccard": c["jaccard"],
|
| 39 |
+
"coverage": c["coverage"],
|
| 40 |
+
"tfidf_cosine": c["tfidf_cosine"],
|
| 41 |
+
},
|
| 42 |
+
"symptoms": symptoms,
|
| 43 |
+
}
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Build the prompt for the LLM, including user symptoms and candidate details
|
| 47 |
+
prompt = self._build_prompt(user_symptoms, enriched, top_k)
|
| 48 |
+
|
| 49 |
+
# Call the LLM to get a new ranking of the candidates
|
| 50 |
+
resp = self.client.chat.completions.create(
|
| 51 |
+
model=self.model,
|
| 52 |
+
messages=[
|
| 53 |
+
{
|
| 54 |
+
"role": "system",
|
| 55 |
+
"content": (
|
| 56 |
+
"You are a ranking engine. You take in a list of candidate conditions "
|
| 57 |
+
"with scores and symptom lists. You must ONLY reorder the given candidates. "
|
| 58 |
+
"Do not invent new conditions. Return a JSON array of objects with keys "
|
| 59 |
+
"`disease` and `rank` (1 = highest)."
|
| 60 |
+
),
|
| 61 |
+
},
|
| 62 |
+
{"role": "user", "content": prompt},
|
| 63 |
+
],
|
| 64 |
+
# Request a deterministic response so we get consistent ranking
|
| 65 |
+
temperature=0.0,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# Parse the LLM response to extract the new ranking order
|
| 69 |
+
content = resp.choices[0].message.content or ""
|
| 70 |
+
try:
|
| 71 |
+
ranking = self._parse_ranking(content)
|
| 72 |
+
except Exception:
|
| 73 |
+
# Fallback: keep original order
|
| 74 |
+
return candidates[:top_k]
|
| 75 |
+
|
| 76 |
+
# Create a mapping of disease to its new rank from the LLM output
|
| 77 |
+
rank_map = {
|
| 78 |
+
item["disease"]: item["rank"]
|
| 79 |
+
for item in ranking
|
| 80 |
+
if isinstance(item, dict) and "disease" in item and "rank" in item
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
# Get all candidates in the map and sort them by their new rank. Candidates not in the map will be ranked lowest.
|
| 84 |
+
reranked = [c for c in candidates if c["disease"] in rank_map]
|
| 85 |
+
reranked.sort(key=lambda x: rank_map.get(x["disease"], 9999))
|
| 86 |
+
|
| 87 |
+
# Append any candidates that were not included in the LLM's ranking at the end of the list
|
| 88 |
+
ranked_diseases = {item["disease"] for item in reranked}
|
| 89 |
+
for candidate in candidates:
|
| 90 |
+
if candidate["disease"] not in ranked_diseases:
|
| 91 |
+
reranked.append(candidate)
|
| 92 |
+
|
| 93 |
+
return reranked[:top_k]
|
| 94 |
+
|
| 95 |
+
# Build the prompt for the LLM, including user symptoms and candidate details
|
| 96 |
+
def _build_prompt(self, user_symptoms, candidates, top_k: int) -> str:
|
| 97 |
+
return json.dumps(
|
| 98 |
+
{
|
| 99 |
+
"user_symptoms": user_symptoms,
|
| 100 |
+
"candidates": candidates,
|
| 101 |
+
"top_k": top_k,
|
| 102 |
+
},
|
| 103 |
+
indent=2,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Parse the LLM response to extract the new ranking order
|
| 107 |
+
def _parse_ranking(self, content: str) -> List[Dict[str, Any]]:
|
| 108 |
+
text = content.strip()
|
| 109 |
+
if text.startswith("```"):
|
| 110 |
+
text = re.sub(r"^```(?:json)?\s*", "", text)
|
| 111 |
+
text = re.sub(r"\s*```$", "", text)
|
| 112 |
+
|
| 113 |
+
parsed = json.loads(text)
|
| 114 |
+
if isinstance(parsed, dict) and "ranking" in parsed:
|
| 115 |
+
parsed = parsed["ranking"]
|
| 116 |
+
if not isinstance(parsed, list):
|
| 117 |
+
raise ValueError("Expected list ranking output.")
|
| 118 |
+
return parsed
|
diagnosis_engine/scoring.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 5 |
+
from .prevalence import get_disease_prevalence
|
| 6 |
+
|
| 7 |
+
# Compute the jaccard score between the user's symptom vector and a disease's symptom vector
|
| 8 |
+
def compute_jaccard(user_vec: np.ndarray, disease_vec: np.ndarray) -> float:
|
| 9 |
+
# Convert to boolean vectors for set operations
|
| 10 |
+
u = user_vec.astype(bool)
|
| 11 |
+
d = disease_vec.astype(bool)
|
| 12 |
+
# Compute the intersection and union of the symptom sets to calculate the Jaccard similarity
|
| 13 |
+
intersection = np.logical_and(u, d).sum()
|
| 14 |
+
union = np.logical_or(u, d).sum()
|
| 15 |
+
if union == 0:
|
| 16 |
+
return 0.0
|
| 17 |
+
return float(intersection / union)
|
| 18 |
+
|
| 19 |
+
# Compute the coverage score: what percentage of the user's symptoms are covered by the disease's symptoms
|
| 20 |
+
def compute_coverage(user_vec: np.ndarray, disease_vec: np.ndarray) -> float:
|
| 21 |
+
# Convert to boolean vectors for set operations
|
| 22 |
+
u = user_vec.astype(bool)
|
| 23 |
+
d = disease_vec.astype(bool)
|
| 24 |
+
# Compute the intersection of the user's symptoms that are present in the disease's symptoms
|
| 25 |
+
# and divide by the total number of user symptoms to get coverage
|
| 26 |
+
intersection = np.logical_and(u, d).sum()
|
| 27 |
+
total_user = u.sum()
|
| 28 |
+
if total_user == 0:
|
| 29 |
+
return 0.0
|
| 30 |
+
return float(intersection / total_user)
|
| 31 |
+
|
| 32 |
+
# Compute a rarity penalty based on disease prevalence, with a stronger penalty for rarer diseases
|
| 33 |
+
def compute_rarity_penalty(prevalence: int) -> float:
|
| 34 |
+
# Keep the penalty btw 0 and 1 so rare diseases are penalized but can still
|
| 35 |
+
# be considered when symptom evidence is very strong.
|
| 36 |
+
return float(np.clip(1.0 / np.sqrt(max(prevalence, 1)), 0.0, 1.0))
|
| 37 |
+
|
| 38 |
+
# Compute a hybrid score (combines jaccard, tfidf cosine similarity, coverage, and rarity penalty with tunable weights)
|
| 39 |
+
def compute_hybrid_score(
|
| 40 |
+
jaccard: float,
|
| 41 |
+
tfidf_cosine: float,
|
| 42 |
+
coverage: float,
|
| 43 |
+
rarity_penalty: float,
|
| 44 |
+
# Set the weights for each part of the hybrid score - the values are chosen based on trial and error
|
| 45 |
+
w_j: float = 0.25,
|
| 46 |
+
w_t: float = 0.25,
|
| 47 |
+
w_c: float = 0.10,
|
| 48 |
+
w_r: float = 0.40,
|
| 49 |
+
) -> float:
|
| 50 |
+
# The weights can be tuned. The rarity penalty is subtracted to discourage rare diseases unless other scores are very high.
|
| 51 |
+
base = (w_j * jaccard) + (w_t * tfidf_cosine) + (w_c * coverage)
|
| 52 |
+
return float(base - (w_r * rarity_penalty))
|
| 53 |
+
|
| 54 |
+
# Score candidate diseases based on multiple metrics and return a ranked list of candidates with their scores
|
| 55 |
+
def score_candidates(
|
| 56 |
+
user_binary_vec: np.ndarray,
|
| 57 |
+
user_tfidf_vec,
|
| 58 |
+
faiss_indices: np.ndarray,
|
| 59 |
+
binary_matrix: np.ndarray,
|
| 60 |
+
tfidf_matrix,
|
| 61 |
+
diseases: List[str],
|
| 62 |
+
disease_counts: Dict[str, int],
|
| 63 |
+
prevalence_map: Dict[str, int],
|
| 64 |
+
mapped_user_symptoms: List[str],
|
| 65 |
+
max_candidates: int = 20,
|
| 66 |
+
top_n: int = 5,
|
| 67 |
+
travel_exposure: bool = False,
|
| 68 |
+
structured_context: Optional[Dict[str, Any]] = None,
|
| 69 |
+
) -> List[Dict[str, Any]]:
|
| 70 |
+
del disease_counts
|
| 71 |
+
|
| 72 |
+
# Compute the user's binary vector and TF-IDF vector for similarity calculations
|
| 73 |
+
user_bin = user_binary_vec[0]
|
| 74 |
+
tfidf_cosines = cosine_similarity(user_tfidf_vec, tfidf_matrix)[0]
|
| 75 |
+
structured_context = structured_context or {}
|
| 76 |
+
|
| 77 |
+
# Define a set of very common symptoms - we can use them to penalize diseases that only match on these
|
| 78 |
+
common_symptoms = {
|
| 79 |
+
"fever",
|
| 80 |
+
"high_fever",
|
| 81 |
+
"mild_fever",
|
| 82 |
+
"headache",
|
| 83 |
+
"runny_nose",
|
| 84 |
+
"cough",
|
| 85 |
+
"fatigue",
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
results = []
|
| 89 |
+
# Loop through the candidate diseases returned by the FAISS index and compute various scores for each candidate
|
| 90 |
+
for rank, idx in enumerate(faiss_indices[0][:max_candidates]):
|
| 91 |
+
disease = diseases[idx]
|
| 92 |
+
disease_bin = binary_matrix[idx]
|
| 93 |
+
prevalence = prevalence_map.get(disease, get_disease_prevalence(disease))
|
| 94 |
+
|
| 95 |
+
# Calculate Jaccard similarity and coverage
|
| 96 |
+
jacc = compute_jaccard(user_bin, disease_bin)
|
| 97 |
+
cov = compute_coverage(user_bin, disease_bin)
|
| 98 |
+
# Filter out candidates that have very low Jaccard similarity and coverage
|
| 99 |
+
if jacc < 0.15 and cov < 0.10:
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
# Calculate TF-IDF cosine similarity and rarity penalty
|
| 103 |
+
tfidf_sim = float(tfidf_cosines[idx])
|
| 104 |
+
rarity_penalty = compute_rarity_penalty(prevalence)
|
| 105 |
+
|
| 106 |
+
# Penalize rare diseases, but allow them when symptom
|
| 107 |
+
# coverage is very high or travel/exposure context supports them.
|
| 108 |
+
if not travel_exposure and prevalence < 100 and cov < 0.60:
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
# Penalize if the disease only matches on common symptoms
|
| 112 |
+
if set(mapped_user_symptoms).issubset(common_symptoms):
|
| 113 |
+
rarity_penalty *= 2.0
|
| 114 |
+
|
| 115 |
+
# Compute the hybrid score combining all metrics
|
| 116 |
+
hybrid = compute_hybrid_score(jacc, tfidf_sim, cov, rarity_penalty)
|
| 117 |
+
|
| 118 |
+
# Adjust the hybrid score if the user indicates symptom progression or a certain duration
|
| 119 |
+
if structured_context.get("progression") == "worsening":
|
| 120 |
+
hybrid += 0.03 * cov
|
| 121 |
+
if structured_context.get("duration"):
|
| 122 |
+
hybrid += 0.02 * min(cov, 1.0)
|
| 123 |
+
|
| 124 |
+
# Adjust the hybrid score based on travel exposure and specific exposures mentioned (i.e mosquito bites)
|
| 125 |
+
exposures = structured_context.get("exposures", [])
|
| 126 |
+
if travel_exposure and exposures:
|
| 127 |
+
hybrid += 0.02
|
| 128 |
+
if any("mosquito" in exposure for exposure in exposures) and prevalence < 100:
|
| 129 |
+
hybrid += 0.08
|
| 130 |
+
if any("travel" in exposure for exposure in exposures) and prevalence < 100:
|
| 131 |
+
hybrid += 0.05
|
| 132 |
+
|
| 133 |
+
results.append(
|
| 134 |
+
{
|
| 135 |
+
"disease": disease,
|
| 136 |
+
"index": int(idx),
|
| 137 |
+
"faiss_rank": int(rank),
|
| 138 |
+
"jaccard": float(jacc),
|
| 139 |
+
"coverage": float(cov),
|
| 140 |
+
"tfidf_cosine": tfidf_sim,
|
| 141 |
+
"rarity_penalty": float(rarity_penalty),
|
| 142 |
+
"hybrid_score": float(hybrid),
|
| 143 |
+
}
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
results.sort(key=lambda x: x["hybrid_score"], reverse=True)
|
| 147 |
+
return results[:top_n]
|
diagnosis_engine/tfidf.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Tuple, List
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 5 |
+
|
| 6 |
+
# Return a single string of all symptoms for a disease, which will be used as the document for TF-IDF vectorization
|
| 7 |
+
def _symptoms_to_text(symptoms: list[str]) -> str:
|
| 8 |
+
return " ".join(symptoms)
|
| 9 |
+
|
| 10 |
+
# Build a TF-IDF matrix for diseases based on their symptoms
|
| 11 |
+
def build_tfidf_matrix(
|
| 12 |
+
collapsed_df: pd.DataFrame,
|
| 13 |
+
) -> Tuple[TfidfVectorizer, np.ndarray]:
|
| 14 |
+
# Convert the list of symptoms for each disease into a single string document for TF-IDF vectorization
|
| 15 |
+
corpus = [_symptoms_to_text(symptoms) for symptoms in collapsed_df["Symptoms"]]
|
| 16 |
+
vectorizer = TfidfVectorizer()
|
| 17 |
+
# Fit the TF-IDF vectorizer on the disease symptom corpus and transform it into a matrix
|
| 18 |
+
tfidf_matrix = vectorizer.fit_transform(corpus)
|
| 19 |
+
return vectorizer, tfidf_matrix
|
| 20 |
+
|
| 21 |
+
# Build a TF-IDF vector for the user's symptoms to compare against the disease TF-IDF matrix
|
| 22 |
+
def build_user_tfidf_vector(
|
| 23 |
+
user_symptoms: list[str], vectorizer: TfidfVectorizer
|
| 24 |
+
) -> np.ndarray:
|
| 25 |
+
text = _symptoms_to_text(user_symptoms)
|
| 26 |
+
# Transform the user's symptom text into a TF-IDF vector using the same vectorizer fitted on the disease corpus
|
| 27 |
+
return vectorizer.transform([text])
|
diagnosis_engine/tropical_diseases.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tropical/Travel-Acquired Diseases
|
| 2 |
+
# These diseases are extremely rare in developed countries
|
| 3 |
+
# and typically acquired through international travel
|
| 4 |
+
# We assume the user is based in the US and has not traveled to tropical regions unless they indicate otherwise
|
| 5 |
+
TROPICAL_DISEASES = {
|
| 6 |
+
"malaria",
|
| 7 |
+
"dengue",
|
| 8 |
+
"typhoid",
|
| 9 |
+
"hepatitis e", # Can be travel-acquired
|
| 10 |
+
"tuberculosis", # Can be travel-acquired in some cases
|
| 11 |
+
"yellow fever", # If present in dataset
|
| 12 |
+
"zika", # If present in dataset
|
| 13 |
+
"chikungunya", # If present in dataset
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
# Check if a disease is considered tropical/travel-acquired based on the predefined set
|
| 17 |
+
def is_tropical_disease(disease_name: str) -> bool:
|
| 18 |
+
"""Check if a disease is considered tropical/travel-acquired"""
|
| 19 |
+
normalized = disease_name.lower().strip()
|
| 20 |
+
return normalized in TROPICAL_DISEASES
|
diagnosis_engine/vocabulary.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from typing import List
|
| 3 |
+
from difflib import get_close_matches
|
| 4 |
+
|
| 5 |
+
# Normalize the symptom
|
| 6 |
+
def normalize_symptom(s: str) -> str:
|
| 7 |
+
s = s.strip().lower()
|
| 8 |
+
s = re.sub(r"[^a-z0-9\s_]", "", s)
|
| 9 |
+
s = s.replace(" ", "_")
|
| 10 |
+
return s
|
| 11 |
+
|
| 12 |
+
# Extract the unique set of symptoms from the collapsed DataFrame
|
| 13 |
+
def extract_unique_symptoms(collapsed_df) -> List[str]:
|
| 14 |
+
unique = set()
|
| 15 |
+
for symptoms in collapsed_df["Symptoms"]:
|
| 16 |
+
for s in symptoms:
|
| 17 |
+
unique.add(s)
|
| 18 |
+
return sorted(unique)
|
| 19 |
+
|
| 20 |
+
# Create a dictionary of common symptom synonyms to map user input to known symptoms
|
| 21 |
+
SYNTAX_SYNONYMS = {
|
| 22 |
+
"body_aches": "muscle_pain",
|
| 23 |
+
"body_ache": "muscle_pain",
|
| 24 |
+
"sore_throat": "throat_irritation",
|
| 25 |
+
"throat_pain": "throat_irritation",
|
| 26 |
+
"shortness_of_breath": "breathlessness",
|
| 27 |
+
"difficulty_breathing": "breathlessness",
|
| 28 |
+
"trouble_breathing": "breathlessness",
|
| 29 |
+
"high_fever": "high_fever",
|
| 30 |
+
"fever": "mild_fever",
|
| 31 |
+
"mild_fever": "mild_fever",
|
| 32 |
+
"runny_nose": "runny_nose",
|
| 33 |
+
"coughing": "cough",
|
| 34 |
+
"cold": "runny_nose",
|
| 35 |
+
"rashes": "skin_rash",
|
| 36 |
+
"rash": "skin_rash",
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
# Map user-provided symptoms to the closest known symptoms in the dataset
|
| 40 |
+
def _token_overlap(a: str, b: str) -> bool:
|
| 41 |
+
a_set = set(a.split("_"))
|
| 42 |
+
b_set = set(b.split("_"))
|
| 43 |
+
return len(a_set.intersection(b_set)) > 0
|
| 44 |
+
|
| 45 |
+
# Map user symptoms to known symptoms using normalization, explicit synonyms, and fuzzy matching
|
| 46 |
+
def map_to_known_symptoms(
|
| 47 |
+
user_symptoms: list[str], all_symptoms: list[str], cutoff: float = 0.85
|
| 48 |
+
) -> list[str]:
|
| 49 |
+
mapped = []
|
| 50 |
+
for s in user_symptoms:
|
| 51 |
+
s_norm = normalize_symptom(s)
|
| 52 |
+
|
| 53 |
+
# explicit synonym dictionary first
|
| 54 |
+
if s_norm in SYNTAX_SYNONYMS:
|
| 55 |
+
candidate = SYNTAX_SYNONYMS[s_norm]
|
| 56 |
+
if candidate in all_symptoms:
|
| 57 |
+
mapped.append(candidate)
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
if s_norm in all_symptoms:
|
| 61 |
+
mapped.append(s_norm)
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
# Use fuzzy matching to find the closest known symptom
|
| 65 |
+
close = get_close_matches(s_norm, all_symptoms, n=1, cutoff=cutoff)
|
| 66 |
+
if close:
|
| 67 |
+
candidate = close[0]
|
| 68 |
+
# Ensure that the match has some token overlap to avoid false positives (e.g. "cold" matching "cough")
|
| 69 |
+
if _token_overlap(s_norm, candidate):
|
| 70 |
+
mapped.append(candidate)
|
| 71 |
+
else:
|
| 72 |
+
# If the closest match doesn't have token overlap, it's probably a false positive, so we'll skip it
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
# Remove duplicates while preserving order
|
| 76 |
+
seen = set()
|
| 77 |
+
normalized_mapped = []
|
| 78 |
+
for item in mapped:
|
| 79 |
+
if item not in seen:
|
| 80 |
+
seen.add(item)
|
| 81 |
+
normalized_mapped.append(item)
|
| 82 |
+
|
| 83 |
+
return normalized_mapped
|
eval/real_query_runner.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Any, Dict, List
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 7 |
+
CASES_PATH = ROOT / "eval" / "real_symptom_queries.json"
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def load_cases() -> List[Dict[str, Any]]:
|
| 11 |
+
return json.loads(CASES_PATH.read_text(encoding="utf-8"))
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def build_deterministic_app():
|
| 15 |
+
from app import MedicalChatbotApp
|
| 16 |
+
|
| 17 |
+
app = MedicalChatbotApp()
|
| 18 |
+
# Keep evaluations stable by bypassing live planner calls during tests.
|
| 19 |
+
app.router.llm_plan = lambda user_input, history, structured_context=None: app.router._fallback_plan( # type: ignore[method-assign]
|
| 20 |
+
user_input,
|
| 21 |
+
structured_context,
|
| 22 |
+
)
|
| 23 |
+
# Preserve the engine's candidate generation but skip nondeterministic reranking.
|
| 24 |
+
app.agents["disease_diagnosis"].reranker.rerank = (
|
| 25 |
+
lambda user_symptoms, candidates, collapsed_df, top_k=5: candidates[:top_k]
|
| 26 |
+
)
|
| 27 |
+
return app
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _resolve_path(payload: Dict[str, Any], path: str) -> Any:
|
| 31 |
+
current: Any = payload
|
| 32 |
+
for part in path.split("."):
|
| 33 |
+
if not isinstance(current, dict):
|
| 34 |
+
return None
|
| 35 |
+
current = current.get(part)
|
| 36 |
+
return current
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def evaluate_case(app, case: Dict[str, Any]) -> Dict[str, Any]:
|
| 40 |
+
state = None
|
| 41 |
+
history = []
|
| 42 |
+
summary = ""
|
| 43 |
+
card_html = ""
|
| 44 |
+
|
| 45 |
+
# Some scenarios intentionally span multiple turns so session state can accumulate.
|
| 46 |
+
for turn in case["turns"]:
|
| 47 |
+
history, state, summary, card_html = app.chat(turn, state)
|
| 48 |
+
|
| 49 |
+
checks = case.get("checks", {})
|
| 50 |
+
failures: List[str] = []
|
| 51 |
+
final_answer = history[-1]["content"] if history else ""
|
| 52 |
+
|
| 53 |
+
for expected in checks.get("final_contains", []):
|
| 54 |
+
if expected not in final_answer:
|
| 55 |
+
failures.append(f"missing final text: {expected}")
|
| 56 |
+
|
| 57 |
+
for path, expected in checks.get("state_equals", {}).items():
|
| 58 |
+
actual = _resolve_path(state or {}, path)
|
| 59 |
+
if actual != expected:
|
| 60 |
+
failures.append(f"{path}: expected {expected!r}, got {actual!r}")
|
| 61 |
+
|
| 62 |
+
for path, expected_values in checks.get("state_contains", {}).items():
|
| 63 |
+
actual = _resolve_path(state or {}, path)
|
| 64 |
+
if not isinstance(actual, list):
|
| 65 |
+
failures.append(f"{path}: expected a list, got {type(actual).__name__}")
|
| 66 |
+
continue
|
| 67 |
+
for value in expected_values:
|
| 68 |
+
if value not in actual:
|
| 69 |
+
failures.append(f"{path}: missing {value!r}")
|
| 70 |
+
|
| 71 |
+
return {
|
| 72 |
+
"id": case["id"],
|
| 73 |
+
"description": case.get("description", ""),
|
| 74 |
+
"turns": case["turns"],
|
| 75 |
+
"passed": not failures,
|
| 76 |
+
"failures": failures,
|
| 77 |
+
"final_answer": final_answer,
|
| 78 |
+
"state": state,
|
| 79 |
+
"summary": summary,
|
| 80 |
+
"card_html": card_html,
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def format_results(results: List[Dict[str, Any]]) -> str:
|
| 85 |
+
lines = []
|
| 86 |
+
passed = 0
|
| 87 |
+
for result in results:
|
| 88 |
+
status = "PASS" if result["passed"] else "FAIL"
|
| 89 |
+
if result["passed"]:
|
| 90 |
+
passed += 1
|
| 91 |
+
lines.append(f"[{status}] {result['id']}: {result['description']}")
|
| 92 |
+
if not result["passed"]:
|
| 93 |
+
for failure in result["failures"]:
|
| 94 |
+
lines.append(f" - {failure}")
|
| 95 |
+
excerpt = result["final_answer"].strip().splitlines()
|
| 96 |
+
if excerpt:
|
| 97 |
+
lines.append(f" answer: {excerpt[0]}")
|
| 98 |
+
lines.append(f"\nPassed {passed}/{len(results)} real-query evaluations.")
|
| 99 |
+
return "\n".join(lines)
|
eval/real_symptom_queries.json
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"id": "emergency_chest_pain",
|
| 4 |
+
"description": "Red-flag respiratory and chest symptoms should trigger emergency guidance.",
|
| 5 |
+
"turns": [
|
| 6 |
+
"I have chest pain and shortness of breath."
|
| 7 |
+
],
|
| 8 |
+
"checks": {
|
| 9 |
+
"final_contains": [
|
| 10 |
+
"medical emergency",
|
| 11 |
+
"Detected red-flag symptoms"
|
| 12 |
+
],
|
| 13 |
+
"state_equals": {
|
| 14 |
+
"last_severity.urgency": "urgent"
|
| 15 |
+
},
|
| 16 |
+
"state_contains": {
|
| 17 |
+
"symptom_context": [
|
| 18 |
+
"chest_pain",
|
| 19 |
+
"breathlessness"
|
| 20 |
+
]
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"id": "vague_fever_needs_clarification",
|
| 26 |
+
"description": "A single vague symptom should produce follow-up questions instead of an overconfident diagnosis.",
|
| 27 |
+
"turns": [
|
| 28 |
+
"I have a fever."
|
| 29 |
+
],
|
| 30 |
+
"checks": {
|
| 31 |
+
"final_contains": [
|
| 32 |
+
"## Follow-Up Questions",
|
| 33 |
+
"Please answer a few of these"
|
| 34 |
+
],
|
| 35 |
+
"state_equals": {
|
| 36 |
+
"last_clarification.needs_clarification": true
|
| 37 |
+
},
|
| 38 |
+
"state_contains": {
|
| 39 |
+
"symptom_context": [
|
| 40 |
+
"mild_fever"
|
| 41 |
+
]
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"id": "cold_like_symptoms_generate_ranked_matches",
|
| 47 |
+
"description": "A realistic upper-respiratory query should yield ranked conditions and preserve natural-language symptom extraction.",
|
| 48 |
+
"turns": [
|
| 49 |
+
"I have a sore throat, runny nose, cough, congestion, and fatigue for 2 days."
|
| 50 |
+
],
|
| 51 |
+
"checks": {
|
| 52 |
+
"final_contains": [
|
| 53 |
+
"## Clinical Summary",
|
| 54 |
+
"## Top Matching Conditions"
|
| 55 |
+
],
|
| 56 |
+
"state_contains": {
|
| 57 |
+
"symptom_context": [
|
| 58 |
+
"throat_irritation",
|
| 59 |
+
"runny_nose",
|
| 60 |
+
"cough",
|
| 61 |
+
"congestion",
|
| 62 |
+
"fatigue"
|
| 63 |
+
]
|
| 64 |
+
},
|
| 65 |
+
"state_equals": {
|
| 66 |
+
"structured_context.duration": "2 days"
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"id": "follow_up_preserves_context_after_travel",
|
| 72 |
+
"description": "A second turn should retain prior symptoms and enrich the stored context with duration, progression, and exposure clues.",
|
| 73 |
+
"turns": [
|
| 74 |
+
"I have fever and cough.",
|
| 75 |
+
"It has been getting worse for 3 days after travel with mosquito bites."
|
| 76 |
+
],
|
| 77 |
+
"checks": {
|
| 78 |
+
"state_contains": {
|
| 79 |
+
"symptom_context": [
|
| 80 |
+
"mild_fever",
|
| 81 |
+
"cough"
|
| 82 |
+
],
|
| 83 |
+
"structured_context.exposures": [
|
| 84 |
+
"travel",
|
| 85 |
+
"mosquito exposure"
|
| 86 |
+
]
|
| 87 |
+
},
|
| 88 |
+
"state_equals": {
|
| 89 |
+
"structured_context.duration": "3 days",
|
| 90 |
+
"structured_context.progression": "worsening"
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"id": "condition_overview_for_named_disease",
|
| 96 |
+
"description": "A disease-focused question should answer with overview and precautions instead of symptom triage.",
|
| 97 |
+
"turns": [
|
| 98 |
+
"What is pneumonia?"
|
| 99 |
+
],
|
| 100 |
+
"checks": {
|
| 101 |
+
"final_contains": [
|
| 102 |
+
"## Condition Overview",
|
| 103 |
+
"Pneumonia",
|
| 104 |
+
"Precautions:"
|
| 105 |
+
]
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
]
|
pytest.ini
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
+
addopts = -p no:cacheprovider
|
requirements.txt
CHANGED
|
@@ -1,25 +1,8 @@
|
|
| 1 |
-
#
|
| 2 |
-
gradio==6.6.0
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
# --- Vector Search ---
|
| 11 |
-
#faiss-cpu==1.13.2
|
| 12 |
-
faiss-cpu==1.7.4
|
| 13 |
-
|
| 14 |
-
# --- Data & Utilities ---
|
| 15 |
-
pandas==2.2.2
|
| 16 |
-
pydantic==2.12.5
|
| 17 |
-
numpy==1.26.4
|
| 18 |
-
|
| 19 |
-
# --- OpenAI Embeddings / Chat ---
|
| 20 |
-
openai>=1.12.0
|
| 21 |
-
|
| 22 |
-
# --- Optional but recommended for HF Spaces ---
|
| 23 |
-
uvicorn==0.29.0
|
| 24 |
-
fastapi==0.115.2
|
| 25 |
-
python-dotenv
|
|
|
|
| 1 |
+
# Hugging Face Space runtime dependencies for MediBot
|
| 2 |
+
gradio==6.6.0
|
| 3 |
+
openai==2.23.0
|
| 4 |
+
faiss-cpu==1.12.0
|
| 5 |
+
pandas==2.2.2
|
| 6 |
+
numpy==1.26.4
|
| 7 |
+
scikit-learn==1.5.1
|
| 8 |
+
python-dotenv==1.0.1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/evaluate_real_queries.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 6 |
+
if str(ROOT) not in sys.path:
|
| 7 |
+
sys.path.insert(0, str(ROOT))
|
| 8 |
+
|
| 9 |
+
from eval.real_query_runner import build_deterministic_app, evaluate_case, format_results, load_cases # noqa: E402
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def main() -> int:
|
| 13 |
+
app = build_deterministic_app()
|
| 14 |
+
# Return a nonzero exit code so this script can be used in automation.
|
| 15 |
+
results = [evaluate_case(app, case) for case in load_cases()]
|
| 16 |
+
print(format_results(results))
|
| 17 |
+
return 0 if all(result["passed"] for result in results) else 1
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
raise SystemExit(main())
|
scripts/smoke_check.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
|
| 6 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 7 |
+
if str(ROOT) not in sys.path:
|
| 8 |
+
sys.path.insert(0, str(ROOT))
|
| 9 |
+
|
| 10 |
+
from diagnosis_engine.vocabulary import map_to_known_symptoms # noqa: E402
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def load_all_symptoms() -> list[str]:
|
| 14 |
+
df = pd.read_csv(ROOT / "data" / "dataset.csv")
|
| 15 |
+
symptoms: set[str] = set()
|
| 16 |
+
for col in [c for c in df.columns if c.lower().startswith("symptom")]:
|
| 17 |
+
for value in df[col].dropna():
|
| 18 |
+
text = str(value).strip().lower()
|
| 19 |
+
if text:
|
| 20 |
+
symptoms.add(text)
|
| 21 |
+
return sorted(symptoms)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def assert_equal(actual, expected, label: str) -> None:
|
| 25 |
+
if actual != expected:
|
| 26 |
+
raise AssertionError(f"{label}: expected {expected}, got {actual}")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main() -> None:
|
| 30 |
+
all_symptoms = load_all_symptoms()
|
| 31 |
+
|
| 32 |
+
assert_equal(
|
| 33 |
+
map_to_known_symptoms(["shortness_of_breath"], all_symptoms),
|
| 34 |
+
["breathlessness"],
|
| 35 |
+
"shortness_of_breath mapping",
|
| 36 |
+
)
|
| 37 |
+
assert_equal(
|
| 38 |
+
map_to_known_symptoms(["chest_pain", "shortness_of_breath"], all_symptoms),
|
| 39 |
+
["chest_pain", "breathlessness"],
|
| 40 |
+
"chest pain plus shortness of breath mapping",
|
| 41 |
+
)
|
| 42 |
+
assert_equal(
|
| 43 |
+
map_to_known_symptoms(["rash"], all_symptoms),
|
| 44 |
+
["skin_rash"],
|
| 45 |
+
"rash mapping",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
print("Smoke checks passed.")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
main()
|
tests/conftest.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _load_app_module():
|
| 13 |
+
os.environ.setdefault("OPENAI_API_KEY", "test-key")
|
| 14 |
+
if str(ROOT) not in sys.path:
|
| 15 |
+
sys.path.insert(0, str(ROOT))
|
| 16 |
+
|
| 17 |
+
spec = importlib.util.spec_from_file_location("medibot_app", ROOT / "app.py")
|
| 18 |
+
module = importlib.util.module_from_spec(spec)
|
| 19 |
+
assert spec.loader is not None
|
| 20 |
+
spec.loader.exec_module(module)
|
| 21 |
+
return module
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.fixture(scope="session")
|
| 25 |
+
def app_module():
|
| 26 |
+
return _load_app_module()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@pytest.fixture
|
| 30 |
+
def medibot_app(app_module, monkeypatch):
|
| 31 |
+
app = app_module.MedicalChatbotApp()
|
| 32 |
+
|
| 33 |
+
monkeypatch.setattr(
|
| 34 |
+
app.agents["disease_diagnosis"].reranker,
|
| 35 |
+
"rerank",
|
| 36 |
+
lambda user_symptoms, candidates, collapsed_df, top_k=5: candidates[:top_k],
|
| 37 |
+
)
|
| 38 |
+
return app
|
tests/test_chat_flow.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def test_chat_returns_clarification_questions_for_ambiguous_symptoms(medibot_app, monkeypatch):
|
| 2 |
+
monkeypatch.setattr(
|
| 3 |
+
medibot_app.router,
|
| 4 |
+
"plan",
|
| 5 |
+
lambda user_input, history, structured_context=None: {
|
| 6 |
+
"steps": [
|
| 7 |
+
{
|
| 8 |
+
"agent": "clarification_agent",
|
| 9 |
+
"payload": {"user_symptoms": ["mild_fever"]},
|
| 10 |
+
"reason": "Need more detail before diagnosis.",
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"agent": "symptom_severity",
|
| 14 |
+
"payload": {"user_symptoms": ["mild_fever"]},
|
| 15 |
+
"reason": "Assess urgency.",
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"agent": "disease_diagnosis",
|
| 19 |
+
"payload": {"user_symptoms": ["mild_fever"]},
|
| 20 |
+
"reason": "Only diagnose if there is enough signal.",
|
| 21 |
+
},
|
| 22 |
+
]
|
| 23 |
+
},
|
| 24 |
+
)
|
| 25 |
+
monkeypatch.setattr(
|
| 26 |
+
medibot_app.agents["clarification_agent"],
|
| 27 |
+
"handle",
|
| 28 |
+
lambda user_symptoms, **kwargs: {
|
| 29 |
+
"needs_clarification": True,
|
| 30 |
+
"reason": "too_few_symptoms",
|
| 31 |
+
"questions": [
|
| 32 |
+
"How long have these symptoms been present?",
|
| 33 |
+
"Are you also experiencing cough?",
|
| 34 |
+
],
|
| 35 |
+
"candidate_preview": [],
|
| 36 |
+
},
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
history, state, summary, card_html = medibot_app.chat("fever", None)
|
| 40 |
+
|
| 41 |
+
assert "Follow-Up Questions" in history[-1]["content"]
|
| 42 |
+
assert state["last_clarification"]["needs_clarification"] is True
|
| 43 |
+
assert "How long have these symptoms been present?" in card_html
|
| 44 |
+
assert "Structured context" in summary
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_chat_reuses_structured_context_on_follow_up_turn(medibot_app, monkeypatch):
|
| 48 |
+
captured_contexts = []
|
| 49 |
+
|
| 50 |
+
def fake_plan(user_input, history, structured_context=None):
|
| 51 |
+
captured_contexts.append(structured_context.copy())
|
| 52 |
+
symptoms = structured_context.get("reported_symptoms") or ["mild_fever"]
|
| 53 |
+
return {
|
| 54 |
+
"steps": [
|
| 55 |
+
{
|
| 56 |
+
"agent": "symptom_severity",
|
| 57 |
+
"payload": {"user_symptoms": symptoms},
|
| 58 |
+
"reason": "Assess urgency from current known symptoms.",
|
| 59 |
+
}
|
| 60 |
+
]
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
monkeypatch.setattr(medibot_app.router, "plan", fake_plan)
|
| 64 |
+
|
| 65 |
+
_, state, _, _ = medibot_app.chat("fever", None)
|
| 66 |
+
_, state, _, _ = medibot_app.chat("for 3 days and getting worse after travel", state)
|
| 67 |
+
|
| 68 |
+
assert captured_contexts[0]["reported_symptoms"] == ["mild_fever"]
|
| 69 |
+
assert captured_contexts[1]["reported_symptoms"] == ["mild_fever"]
|
| 70 |
+
assert captured_contexts[1]["duration"] == "3 days"
|
| 71 |
+
assert captured_contexts[1]["progression"] == "worsening"
|
| 72 |
+
assert "travel" in captured_contexts[1]["exposures"]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_chat_returns_emergency_message_for_red_flag_symptoms(medibot_app, monkeypatch):
|
| 76 |
+
monkeypatch.setattr(
|
| 77 |
+
medibot_app.router,
|
| 78 |
+
"plan",
|
| 79 |
+
lambda user_input, history, structured_context=None: {
|
| 80 |
+
"steps": [
|
| 81 |
+
{
|
| 82 |
+
"agent": "symptom_severity",
|
| 83 |
+
"payload": {"user_symptoms": ["chest_pain", "breathlessness"]},
|
| 84 |
+
"reason": "Red-flag triage.",
|
| 85 |
+
}
|
| 86 |
+
]
|
| 87 |
+
},
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
history, state, _, _ = medibot_app.chat("chest pain and shortness of breath", None)
|
| 91 |
+
|
| 92 |
+
assert "medical emergency" in history[-1]["content"].lower()
|
| 93 |
+
assert state["last_severity"]["urgency"] == "urgent"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_chat_can_answer_condition_overview_without_diagnosis(medibot_app, monkeypatch):
|
| 97 |
+
monkeypatch.setattr(
|
| 98 |
+
medibot_app.router,
|
| 99 |
+
"plan",
|
| 100 |
+
lambda user_input, history, structured_context=None: {
|
| 101 |
+
"steps": [
|
| 102 |
+
{
|
| 103 |
+
"agent": "disease_description",
|
| 104 |
+
"payload": {"disease": "pneumonia"},
|
| 105 |
+
"reason": "Explain the condition.",
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"agent": "precaution_advisor",
|
| 109 |
+
"payload": {"disease": "pneumonia"},
|
| 110 |
+
"reason": "Provide precautions.",
|
| 111 |
+
},
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
history, _, _, _ = medibot_app.chat("what is pneumonia", None)
|
| 117 |
+
|
| 118 |
+
assert "Condition Overview" in history[-1]["content"]
|
| 119 |
+
assert "Pneumonia" in history[-1]["content"]
|
| 120 |
+
assert "Precautions:" in history[-1]["content"]
|
tests/test_helpers.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def test_extract_structured_context_captures_duration_progression_exposure_and_symptoms(app_module, medibot_app):
|
| 2 |
+
context = app_module.extract_structured_context(
|
| 3 |
+
"I have fever and cough for 3 days and it is getting worse after travel with mosquito bites.",
|
| 4 |
+
medibot_app.all_symptoms,
|
| 5 |
+
)
|
| 6 |
+
|
| 7 |
+
assert "mild_fever" in context["reported_symptoms"]
|
| 8 |
+
assert "cough" in context["reported_symptoms"]
|
| 9 |
+
assert context["duration"] == "3 days"
|
| 10 |
+
assert context["progression"] == "worsening"
|
| 11 |
+
assert "travel" in context["exposures"]
|
| 12 |
+
assert "mosquito exposure" in context["exposures"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_merge_structured_context_deduplicates_and_preserves_existing(app_module):
|
| 16 |
+
merged = app_module.merge_structured_context(
|
| 17 |
+
{
|
| 18 |
+
"reported_symptoms": ["cough", "mild_fever"],
|
| 19 |
+
"duration": "2 days",
|
| 20 |
+
"progression": None,
|
| 21 |
+
"exposures": ["travel"],
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"reported_symptoms": ["mild_fever", "fatigue"],
|
| 25 |
+
"duration": None,
|
| 26 |
+
"progression": "worsening",
|
| 27 |
+
"exposures": ["travel", "sick contacts"],
|
| 28 |
+
},
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
assert merged["reported_symptoms"] == ["cough", "mild_fever", "fatigue"]
|
| 32 |
+
assert merged["duration"] == "2 days"
|
| 33 |
+
assert merged["progression"] == "worsening"
|
| 34 |
+
assert merged["exposures"] == ["travel", "sick contacts"]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_router_fallback_uses_structured_context_when_follow_up_has_no_new_symptoms(medibot_app):
|
| 38 |
+
planned = medibot_app.router._fallback_plan(
|
| 39 |
+
"they are getting worse today",
|
| 40 |
+
{"reported_symptoms": ["mild_fever", "cough"]},
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
assert "steps" in planned
|
| 44 |
+
assert planned["steps"][0]["agent"] == "clarification_agent"
|
| 45 |
+
assert planned["steps"][0]["payload"]["user_symptoms"] == ["mild_fever", "cough"]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_dataset_has_required_core_records(app_module):
|
| 49 |
+
data = app_module.load_datasets()
|
| 50 |
+
|
| 51 |
+
diseases = set(data["symptom_disease"]["Disease"])
|
| 52 |
+
assert "pneumonia" in diseases
|
| 53 |
+
assert "" not in diseases
|
| 54 |
+
assert data["severity"]["weight"].notna().all()
|
| 55 |
+
|
| 56 |
+
pneumonia_desc = data["description"].loc[data["description"]["Disease"] == "pneumonia"]
|
| 57 |
+
pneumonia_prec = data["precaution"].loc[data["precaution"]["Disease"] == "pneumonia"]
|
| 58 |
+
assert not pneumonia_desc.empty
|
| 59 |
+
assert not pneumonia_prec.empty
|
tests/test_real_symptom_queries.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 6 |
+
if str(ROOT) not in sys.path:
|
| 7 |
+
sys.path.insert(0, str(ROOT))
|
| 8 |
+
|
| 9 |
+
from eval.real_query_runner import build_deterministic_app, evaluate_case, load_cases
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_real_symptom_queries_cover_realistic_user_prompts():
|
| 13 |
+
app = build_deterministic_app()
|
| 14 |
+
failures = []
|
| 15 |
+
|
| 16 |
+
for case in load_cases():
|
| 17 |
+
result = evaluate_case(app, case)
|
| 18 |
+
if not result["passed"]:
|
| 19 |
+
failure_text = ", ".join(result["failures"])
|
| 20 |
+
failures.append(f"{case['id']}: {failure_text}")
|
| 21 |
+
|
| 22 |
+
assert not failures, "\n".join(failures)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if __name__ == "__main__":
|
| 26 |
+
# Allow the file to be run directly from editor helpers like Code Runner.
|
| 27 |
+
test_real_symptom_queries_cover_realistic_user_prompts()
|
| 28 |
+
print("Real symptom query evaluation passed.")
|