How hossyehiaa/medai works
Purpose and Entry Points
medAI is a CLI-oriented clinical decision-support RAG system for USPSTF June 2023 depression and suicide-risk screening guidance. Primary operations are document indexing through ingest.py, interactive/direct clinical querying through search_cli.py, and a self-building demonstration through final_demo.py. The end-to-end orchestrator is src/pipeline.py.
Configuration and Runtime Boundaries
Central runtime policy—model names, confidence thresholds, retrieval boosts, and API configuration—is concentrated in configs/settings.py. Python runs the application, with local PDF inputs under raw_documents/, derived artifacts under data/, and an OpenRouter API key supplied via .env. The external generation dependency is OpenRouter; local retrieval depends on ChromaDB, sentence-transformer embeddings, BM25, and a cross-encoder reranker.
Ingestion and Index Construction
The ingestion stage converts guideline PDFs into retrievable records:
• PDF extraction uses a dual backend with fallback in src/ingestion/pdf_parser.py and table handling in src/ingestion/table_extractor.py.
• Content is normalized and segmented by src/ingestion/text_cleaner.py and src/ingestion/chunker.py.
• src/ingestion/embedder.py produces 384-dimensional MiniLM embeddings.
• ingest.py persists chunk data and creates the local vector index. Existing parsed output is reused where possible, avoiding expensive re-parsing.
Retrieval and Ranking
src/retrieval/retrieval_manager.py coordinates hybrid evidence retrieval. Dense similarity search is backed by src/retrieval/vector_store.py; sparse lexical retrieval is backed by src/retrieval/bm25_index.py. src/retrieval/hybrid_search.py fuses their rankings using reciprocal-rank fusion, applies population-specific boosts, and sends candidates to src/retrieval/reranker.py for cross-encoder ranking. The resulting evidence is section-prior adjusted, diversity constrained across source documents, and confidence gated before generation.
Safety and Decision Gates
All query handling begins with src/safety/guardrails.py. It blocks multilingual imminent-crisis, medication/dosing, and prompt-injection patterns before retrieval or LLM invocation. Crisis requests receive emergency referral guidance; dosing requests receive an out-of-scope response. A low retrieval-confidence decision also refuses unsupported answers. Post-generation safety responsibilities include citation verification, schema checks, and mandatory disclaimer behavior.
Grounded Generation
For accepted evidence, src/generation/prompt_builder.py constructs an attributed six-section clinical response prompt from retrieved chunks. src/generation/llm_client.py calls OpenRouter, using DeepSeek V3 as the primary model and configured Llama/Qwen fallbacks. Generated citations are verified against source text; a failed verification can trigger one stricter retry. If service/model fallbacks are exhausted, generation degrades to a safe mock/refusal path rather than unsupported clinical content.
Evaluation and Operational Outputs
Evaluation is separated from production flow in src/evaluation/retrieval_evaluator.py, src/evaluation/end_to_end_evaluator.py, and src/evaluation/tuning_experiment.py. These consume benchmark queries and inspect retrieval, safety, citation, and generation behavior, writing reports into data/. Persisted reports and baseline metrics provide evidence of tuning state, while final_demo.py offers a repeatable operational walkthrough.
Main entry points: pipeline.py Pipeline orchestrator · llm_client.py OpenRouter client · guardrails.py Safety guardrails · retrieval_manager.py Retrieval manager
Components 20
Ingestion
- Guideline PDFs
- Indexing CLI
ingest.py - PDF extraction · Uses a fallback parser and table handling.
src/ingestion/pdf_parser.py - Normalize & chunk
src/ingestion/chunker.py - MiniLM embedder · Produces 384-dimensional vectors.
src/ingestion/embedder.py - Derived artifacts · Parsed output is reused to avoid reparsing.
Retrieval
- Retrieval manager
src/retrieval/retrieval_manager.py - Chroma vector search
src/retrieval/vector_store.py - BM25 search
src/retrieval/bm25_index.py - Hybrid fusion & rerank · RRF, population boosts, cross-encoder ranking, diversity, and confidence gating.
src/retrieval/hybrid_search.py
Query & Generation
- Clinical query CLI
search_cli.py - Safety guardrails · Blocks crisis, dosing, and prompt-injection requests.
src/safety/guardrails.py - Attributed prompt builder · Builds a six-section clinical response prompt.
src/generation/prompt_builder.py - OpenRouter client · Uses DeepSeek V3 with Llama/Qwen fallbacks and safe degradation.
src/generation/llm_client.py - OpenRouter
Evaluation
- Evaluation suite · Assesses retrieval, safety, citations, generation, and tuning.
src/evaluation/end_to_end_evaluator.py - Reports & baselines
- Repeatable demo
final_demo.py
Other components
- Pipeline orchestrator
src/pipeline.py - Runtime settings · Models, thresholds, boosts, and API configuration.
configs/settings.py
Connections 24
- Guideline PDFs → Indexing CLI: input
- Indexing CLI → PDF extraction: extracts
- PDF extraction → Normalize & chunk: text and tables
- Normalize & chunk → MiniLM embedder: chunks
- MiniLM embedder → Derived artifacts: vectors and chunk records
- Pipeline orchestrator → Indexing CLI: orchestrates indexing
- Runtime settings → Pipeline orchestrator: runtime policy
- Clinical query CLI → Safety guardrails: query
- Pipeline orchestrator → Safety guardrails: orchestrates queries
- Safety guardrails → Retrieval manager: accepted queries
- Retrieval manager → Chroma vector search: dense search
- Retrieval manager → BM25 search: sparse search
- Chroma vector search → Hybrid fusion & rerank: dense candidates
- BM25 search → Hybrid fusion & rerank: lexical candidates
- Derived artifacts → Chroma vector search: indexed embeddings
- Derived artifacts → BM25 search: chunk corpus
- Hybrid fusion & rerank → Attributed prompt builder: confidence-gated evidence
- Attributed prompt builder → OpenRouter client: grounded prompt
- OpenRouter client → OpenRouter: generation request
- OpenRouter → OpenRouter client: model response
- OpenRouter client → Safety guardrails: citation and schema checks
- Evaluation suite → Pipeline orchestrator: exercises production flow
- Evaluation suite → Reports & baselines: writes metrics and reports
- Repeatable demo → Pipeline orchestrator: runs walkthrough