CoolFace
Apppublic

zakaria-ch49/Medical-Question-Answering-with-Retrieval-Augmented-Generation_RAG

sourceHugging Facemitupdated 7mo agoView on Hugging Face
1likes
App README

<div align="center">

πŸ₯ Medical RAG Assistant

AI-Powered Medical Question Answering with Retrieval-Augmented Generation

![πŸš€ Live Demo](https://huggingface.co/spaces/zakaria-ch49/Medical-Question-Answering-with-Retrieval-Augmented-Generation_RAG) ![GitHub](https://github.com/zakaria-ch49/Medical-Question-Answering-with-RAG) ![License: MIT](LICENSE) ![Python 3.11](https://python.org) ![CI Tests](https://github.com/zakaria-ch49/Medical-Question-Answering-with-RAG/actions/workflows/ci.yml)

</div>


πŸ†• What's New

UpdateDescription
πŸ”΄ openFDA dual-sourceDrug labels from the FDA API are now fetched in parallel with PubMed. If PubMed times out, FDA results are used automatically β€” and vice-versa.
πŸ”΄ Intelligent query cleaningFDA queries are automatically converted from PubMed MeSH syntax to plain FDA-compatible search terms, with progressive fallback variants.
πŸ”΄ PubMed resilienceRetry on ReadTimeout / ConnectTimeout with exponential backoff. Failing batches are recursively split in two (up to 2 levels) instead of being dropped entirely.
πŸ”΄ Faster responsesBatch size reduced from 100 β†’ 20, timeout scaled per article (2 s/article), backoff reduced from 1.5 s β†’ 0.5 s. Typical response time: 45–90 s vs. previously 10 min.
πŸ”΄ Structured AI answersSystem prompt redesigned: responses now follow a strict Answer / Key Points / Disclaimer format β€” concise, professional, no emojis, full medical terminology, source citations.
πŸ”΄ Source badges in UIDocuments from PubMed show a clickable PMID link; FDA drug labels show an orange FDA Drug Label badge. Metrics panel shows PubMed and FDA counts separately.

<br/>

An intelligent medical assistant that retrieves real scientific evidence from PubMed and generates structured, evidence-based answers using state-of-the-art LLMs.

⚠️ For educational purposes only β€” not a substitute for professional medical advice.

</div>


🎯 Try the Live Demo

<div align="center">

![Open in Hugging Face Spaces](https://huggingface.co/spaces/zakaria-ch49/Medical-Question-Answering-with-Retrieval-Augmented-Generation_RAG)

</div>


✨ Features

FeatureDetail
πŸ”Real-time PubMed SearchFetches up-to-date scientific articles from NCBI’s PubMed database (E-utilities API)
πŸ“ŠopenFDA Drug LabelsFetches official FDA drug label data in parallel with PubMed β€” indications, mechanism, dosage, warnings
🧠BGE Semantic EmbeddingsBAAI/bge-base-en β€” state-of-the-art biomedical embedding model
⚑FAISS Vector StoreLightning-fast similarity search across thousands of documents
🌐Auto Query TranslationConverts any language / typo / vague question into a precise PubMed MeSH query
πŸ”„Resilient Network LayerHTTPAdapter + Retry with exponential backoff, ReadTimeout retries, recursive batch splitting
πŸ€–Structured AI AnswersFixed Answer / Key Points / Disclaimer format β€” concise, cited, professional medical terminology
🌊Streaming ResponsesReal-time token-by-token output for a smooth user experience
🌍MultilingualResponds in the same language as the user’s question
🐳DockerizedOne-command deployment anywhere

πŸ“ Architecture

User Question (any language)
        β”‚
        β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚          Streamlit Web UI                     β”‚
β”‚          src/streamlit_app.py                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚   Query Translator         β”‚   OpenRouter API
     β”‚   (LLM β†’ MeSH English)     β”‚ ──────────────────
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚  optimised PubMed query
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚   PubMed Downloader        β”‚   src/download_pubmed.py
     β”‚   NCBI E-utilities API     β”‚   (batch fetch, up to 200 articles)
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚  title + abstract (preprocessed)
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚   BGE Embedding Engine     β”‚   src/bio_clinical_embeddings.py
     β”‚   BAAI/bge-base-en         β”‚
     β”‚   FAISS Vector Index       β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚  top-k relevant documents (BGE score ≀ 0.30)
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚   OpenRouter LLM           β”‚   src/open_router.py
     β”‚   Qwen3-235B-A22B-Thinking β”‚   (streaming SSE)
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚
         Structured Medical Answer
         (cited, evidence-graded, multilingual)

πŸ”¬ RAG Pipeline β€” Step by Step

StepModuleDescription
1 β€” Query Translationopen_router.pyUser’s question (any language / typos) β†’ precise PubMed MeSH query in English via LLM
2 β€” Dual-Source Retrievaldownload_pubmed.pyPubMed (articles) + openFDA (drug labels) fetched in parallel β€” auto-fallback if one source fails
3 β€” Preprocessingdownload_pubmed.pyClean text: strip MeSH tags, normalize whitespace, remove special chars
4 β€” Vectorizationbio_clinical_embeddings.pyEmbed all documents with BAAI/bge-base-en β†’ FAISS index
5 β€” Semantic Searchbio_clinical_embeddings.pyRetrieve top-k documents by cosine similarity (BGE score threshold ≀ 0.30)
6 β€” Answer Generationopen_router.pyStream structured Answer / Key Points / Disclaimer response via Qwen3-235B

πŸ“ Project Structure

medical-rag-assistant/
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ streamlit_app.py            # πŸ–₯️  Streamlit web interface (main entry point)
β”‚   β”œβ”€β”€ main.py                     # ⌨️  CLI interface (interactive terminal mode)
β”‚   β”œβ”€β”€ download_pubmed.py          # πŸ“₯  PubMed batch downloader + text preprocessor
β”‚   β”œβ”€β”€ bio_clinical_embeddings.py  # 🧠  BGE embeddings + FAISS vector store
β”‚   └── open_router.py              # πŸ€–  OpenRouter LLM client (streaming + sync)
β”‚
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ conftest.py                 # Pytest configuration & shared fixtures
β”‚   β”œβ”€β”€ test_download_pubmed.py     # Unit tests β€” PubMed downloader
β”‚   β”œβ”€β”€ test_bio_clinical_embeddings.py  # Unit tests β€” embeddings & search
β”‚   └── test_open_router.py         # Unit tests β€” OpenRouter client
β”‚
β”œβ”€β”€ data/
β”‚   └── cache/                      # πŸ’Ύ  Auto-generated PubMed cache (git-ignored)
β”‚
β”œβ”€β”€ .github/workflows/ci.yml        # βœ…  GitHub Actions CI (pytest on every push)
β”œβ”€β”€ .env.example                    # πŸ”‘  Environment variable template
β”œβ”€β”€ Dockerfile                      # 🐳  Container image definition
β”œβ”€β”€ docker-compose.yml              # 🐳  One-command local deployment
β”œβ”€β”€ Makefile                        # πŸ› οΈ  Developer shortcuts (install, run, clean…)
β”œβ”€β”€ requirements.txt                # πŸ“¦  Full Python dependencies
└── requirements-ci.txt             # πŸ“¦  Lightweight CI-only dependencies

πŸš€ Quick Start

Prerequisites

  • β€”Python 3.11+
  • β€”An OpenRouter API key β€” free tier available

1 Β· Clone & configure

bash
git clone https://github.com/zakaria-ch49/Medical-Question-Answering-with-RAG.git
cd Medical-Question-Answering-with-RAG

cp .env.example .env
# Open .env and paste your OPENROUTER_API_KEY

2 Β· Install dependencies

bash
pip install -r requirements.txt
# or: make install

3 Β· Launch the web UI

bash
streamlit run src/streamlit_app.py
# or: make run

Open http://localhost:8501 in your browser.

4 Β· (Optional) CLI mode

bash
python src/main.py
# or: make cli

🐳 Docker Deployment

bash
# Build and start (detached)
docker compose up --build -d

# Follow logs
docker compose logs -f

# Stop
docker compose down

The app is exposed on port 7860 (HuggingFace Spaces compatible).


βœ… Running Tests

bash
pip install -r requirements-ci.txt
pytest tests/ -v

The test suite uses mocks β€” no internet connection or GPU required.


βš™οΈ Environment Variables

VariableDescriptionRequired
OPENROUTER_API_KEYYour OpenRouter API keyβœ… Yes
HF_TOKENHugging Face token (optional, for private models)⚑ Optional

Create a .env file from the template:

bash
cp .env.example .env

πŸ“¦ Tech Stack

TechnologyVersionRole
StreamlitlatestInteractive web UI
LangChainlatestRAG pipeline orchestration
BAAI/bge-base-enβ€”Biomedical text embeddings
FAISScpuVector similarity search
OpenRouterβ€”Unified LLM API gateway
Qwen3-235B-A22B-Thinking235B / 22B activeAnswer generation (MoE, streaming)
PubMed NCBI APIE-utilitiesScientific medical literature
openFDA APIdrug/labelOfficial FDA drug label database
Dockerβ€”Containerized deployment
pytestβ€”Unit testing
LLM β€” `qwen/qwen3-vl-235b-a22b-thinking` - 235 billion total parameters Β· 22 billion active (Mixture of Experts) - Advanced chain-of-thought reasoning Β· Multilingual Β· Strong medical comprehension

⚠️ Limitations

  • β€”πŸŒ Internet required β€” PubMed and openFDA articles are fetched live; no offline mode
  • β€”πŸ’ Cold start β€” BGE embedding model loads on first query (~30 s on CPU)
  • β€”πŸ“„ Abstracts only β€” Full-text articles are not retrieved, only titles & abstracts
  • β€”πŸ”‘ API key required β€” An OpenRouter key is needed to generate answers
  • β€”πŸ₯ Not for clinical use β€” For educational and research purposes only; always consult a healthcare professional
  • β€”πŸŒ English-biased β€” PubMed is predominantly in English; non-English queries may return fewer results

πŸ—ΊοΈ Roadmap

StatusFeature
βœ… DonePubMed real-time retrieval
βœ… DoneopenFDA drug label retrieval (parallel, auto-fallback)
βœ… DoneBGE semantic search with FAISS
βœ… DoneStreaming LLM answers
βœ… DoneStructured AI responses (Answer / Key Points / Disclaimer)
βœ… DonePubMed network resilience (retry + backoff + batch splitting)
βœ… DoneSource badges in UI (PubMed vs FDA)
βœ… DoneDocker deployment on Hugging Face Spaces
βœ… DoneCI/CD with GitHub Actions
πŸ”„ PlannedFull-text article retrieval (PMC Open Access)
πŸ”„ PlannedChat history / conversation memory
πŸ”„ PlannedExport answers to PDF
πŸ”„ PlannedGPU acceleration for embeddings
πŸ’‘ Contributions welcome! Feel free to open issues or pull requests.

πŸ“„ License

This project is licensed under the MIT License β€” see the LICENSE file for details.


<div align="center">

Made with ❀️ by Zakaria CHADADI for medical AI research

![πŸš€ Try the Demo](https://huggingface.co/spaces/zakaria-ch49/Medical-Question-Answering-with-Retrieval-Augmented-Generation_RAG)

</div>