# hossyehiaa/medai architecture

> Architecture diagram of the GitHub repository hossyehiaa/medai, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-08-19). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/hossyehiaa/medai
- Repository: https://github.com/hossyehiaa/medai

## Overview

#### 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: [`src/pipeline.py`](https://github.com/hossyehiaa/medai/blob/main/src/pipeline.py) (Pipeline orchestrator), [`src/generation/llm_client.py`](https://github.com/hossyehiaa/medai/blob/main/src/generation/llm_client.py) (OpenRouter client), [`src/safety/guardrails.py`](https://github.com/hossyehiaa/medai/blob/main/src/safety/guardrails.py) (Safety guardrails), [`src/retrieval/retrieval_manager.py`](https://github.com/hossyehiaa/medai/blob/main/src/retrieval/retrieval_manager.py) (Retrieval manager)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_ingestion["Ingestion"]
  node_raw_pdfs["Guideline PDFs<br/>source documents"]
  node_ingest_cli["Indexing CLI<br/>entry point<br/>[ingest.py]"]
  node_pdf_extract["PDF extraction<br/>parser + tables<br/>[pdf_parser.py]"]
  node_normalize_chunk["Normalize &amp; chunk<br/>text pipeline<br/>[chunker.py]"]
  node_embedder["MiniLM embedder<br/>embedding model<br/>[embedder.py]"]
  node_local_data[("Derived artifacts<br/>parsed chunks + indexes")]
end

subgraph group_retrieval["Retrieval"]
  node_retrieval_manager{{"Retrieval manager<br/>hybrid retrieval coordinator"}}
  node_vector_store[("Chroma vector search<br/>dense retrieval<br/>[vector_store.py]")]
  node_bm25["BM25 search<br/>sparse retrieval<br/>[bm25_index.py]"]
  node_hybrid_rank["Hybrid fusion &amp; rerank<br/>evidence ranking<br/>[hybrid_search.py]"]
end

subgraph group_answering["Query &amp; Generation"]
  node_search_cli["Clinical query CLI<br/>entry point<br/>[search_cli.py]"]
  node_guardrails["Safety guardrails<br/>pre/post safety gate<br/>[guardrails.py]"]
  node_prompt_builder["Attributed prompt builder<br/>grounding formatter<br/>[prompt_builder.py]"]
  node_llm_client["OpenRouter client<br/>generation gateway<br/>[llm_client.py]"]
  node_openrouter(("OpenRouter<br/>external LLM service"))
end

subgraph group_evaluation["Evaluation"]
  node_evaluation["Evaluation suite<br/>benchmark and tuning"]
  node_reports["Reports &amp; baselines<br/>operational evidence"]
  node_demo["Repeatable demo<br/>operational walkthrough<br/>[final_demo.py]"]
end

node_pipeline{{"Pipeline orchestrator<br/>workflow coordinator<br/>[pipeline.py]"}}
node_settings["Runtime settings<br/>policy configuration<br/>[settings.py]"]

node_raw_pdfs -->|"input"| node_ingest_cli
node_ingest_cli -->|"extracts"| node_pdf_extract
node_pdf_extract -->|"text and tables"| node_normalize_chunk
node_normalize_chunk -->|"chunks"| node_embedder
node_embedder -->|"vectors and chunk records"| node_local_data
node_pipeline -->|"orchestrates indexing"| node_ingest_cli
node_settings -.->|"runtime policy"| node_pipeline
node_search_cli -->|"query"| node_guardrails
node_pipeline -->|"orchestrates queries"| node_guardrails
node_guardrails -->|"accepted queries"| node_retrieval_manager
node_retrieval_manager -->|"dense search"| node_vector_store
node_retrieval_manager -->|"sparse search"| node_bm25
node_vector_store -->|"dense candidates"| node_hybrid_rank
node_bm25 -->|"lexical candidates"| node_hybrid_rank
node_local_data -->|"indexed embeddings"| node_vector_store
node_local_data -->|"chunk corpus"| node_bm25
node_hybrid_rank -->|"confidence-gated evidence"| node_prompt_builder
node_prompt_builder -->|"grounded prompt"| node_llm_client
node_llm_client -->|"generation request"| node_openrouter
node_openrouter -->|"model response"| node_llm_client
node_llm_client -->|"citation and schema checks"| node_guardrails
node_evaluation -.->|"exercises production flow"| node_pipeline
node_evaluation -->|"writes metrics and reports"| node_reports
node_demo -->|"runs walkthrough"| node_pipeline

click node_ingest_cli "https://github.com/hossyehiaa/medai/blob/main/ingest.py"
click node_pdf_extract "https://github.com/hossyehiaa/medai/blob/main/src/ingestion/pdf_parser.py"
click node_normalize_chunk "https://github.com/hossyehiaa/medai/blob/main/src/ingestion/chunker.py"
click node_embedder "https://github.com/hossyehiaa/medai/blob/main/src/ingestion/embedder.py"
click node_pipeline "https://github.com/hossyehiaa/medai/blob/main/src/pipeline.py"
click node_settings "https://github.com/hossyehiaa/medai/blob/main/configs/settings.py"
click node_search_cli "https://github.com/hossyehiaa/medai/blob/main/search_cli.py"
click node_guardrails "https://github.com/hossyehiaa/medai/blob/main/src/safety/guardrails.py"
click node_retrieval_manager "https://github.com/hossyehiaa/medai/blob/main/src/retrieval/retrieval_manager.py"
click node_vector_store "https://github.com/hossyehiaa/medai/blob/main/src/retrieval/vector_store.py"
click node_bm25 "https://github.com/hossyehiaa/medai/blob/main/src/retrieval/bm25_index.py"
click node_hybrid_rank "https://github.com/hossyehiaa/medai/blob/main/src/retrieval/hybrid_search.py"
click node_prompt_builder "https://github.com/hossyehiaa/medai/blob/main/src/generation/prompt_builder.py"
click node_llm_client "https://github.com/hossyehiaa/medai/blob/main/src/generation/llm_client.py"
click node_evaluation "https://github.com/hossyehiaa/medai/blob/main/src/evaluation/end_to_end_evaluator.py"
click node_demo "https://github.com/hossyehiaa/medai/blob/main/final_demo.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_raw_pdfs,node_ingest_cli,node_pdf_extract,node_normalize_chunk,node_embedder,node_local_data toneBlue
class node_retrieval_manager,node_vector_store,node_bm25,node_hybrid_rank toneAmber
class node_search_cli,node_guardrails,node_prompt_builder,node_llm_client,node_openrouter toneMint
class node_evaluation,node_reports,node_demo toneRose
class node_pipeline,node_settings toneNeutral
```

## Components

### Ingestion

- **Guideline PDFs**: source documents
- [Indexing CLI](https://github.com/hossyehiaa/medai/blob/main/ingest.py): entry point · `ingest.py`
- [PDF extraction](https://github.com/hossyehiaa/medai/blob/main/src/ingestion/pdf_parser.py): parser + tables · Uses a fallback parser and table handling. · `src/ingestion/pdf_parser.py`
- [Normalize & chunk](https://github.com/hossyehiaa/medai/blob/main/src/ingestion/chunker.py): text pipeline · `src/ingestion/chunker.py`
- [MiniLM embedder](https://github.com/hossyehiaa/medai/blob/main/src/ingestion/embedder.py): embedding model · Produces 384-dimensional vectors. · `src/ingestion/embedder.py`
- **Derived artifacts**: parsed chunks + indexes · Parsed output is reused to avoid reparsing.

### Retrieval

- [Retrieval manager](https://github.com/hossyehiaa/medai/blob/main/src/retrieval/retrieval_manager.py): hybrid retrieval coordinator · `src/retrieval/retrieval_manager.py`
- [Chroma vector search](https://github.com/hossyehiaa/medai/blob/main/src/retrieval/vector_store.py): dense retrieval · `src/retrieval/vector_store.py`
- [BM25 search](https://github.com/hossyehiaa/medai/blob/main/src/retrieval/bm25_index.py): sparse retrieval · `src/retrieval/bm25_index.py`
- [Hybrid fusion & rerank](https://github.com/hossyehiaa/medai/blob/main/src/retrieval/hybrid_search.py): evidence ranking · RRF, population boosts, cross-encoder ranking, diversity, and confidence gating. · `src/retrieval/hybrid_search.py`

### Query & Generation

- [Clinical query CLI](https://github.com/hossyehiaa/medai/blob/main/search_cli.py): entry point · `search_cli.py`
- [Safety guardrails](https://github.com/hossyehiaa/medai/blob/main/src/safety/guardrails.py): pre/post safety gate · Blocks crisis, dosing, and prompt-injection requests. · `src/safety/guardrails.py`
- [Attributed prompt builder](https://github.com/hossyehiaa/medai/blob/main/src/generation/prompt_builder.py): grounding formatter · Builds a six-section clinical response prompt. · `src/generation/prompt_builder.py`
- [OpenRouter client](https://github.com/hossyehiaa/medai/blob/main/src/generation/llm_client.py): generation gateway · Uses DeepSeek V3 with Llama/Qwen fallbacks and safe degradation. · `src/generation/llm_client.py`
- **OpenRouter**: external LLM service

### Evaluation

- [Evaluation suite](https://github.com/hossyehiaa/medai/blob/main/src/evaluation/end_to_end_evaluator.py): benchmark and tuning · Assesses retrieval, safety, citations, generation, and tuning. · `src/evaluation/end_to_end_evaluator.py`
- **Reports & baselines**: operational evidence
- [Repeatable demo](https://github.com/hossyehiaa/medai/blob/main/final_demo.py): operational walkthrough · `final_demo.py`

### Other components

- [Pipeline orchestrator](https://github.com/hossyehiaa/medai/blob/main/src/pipeline.py): workflow coordinator · `src/pipeline.py`
- [Runtime settings](https://github.com/hossyehiaa/medai/blob/main/configs/settings.py): policy configuration · Models, thresholds, boosts, and API configuration. · `configs/settings.py`

## Connections

- 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
