44 KiB
🏥 Agentic ICD-10-CM Autonomous Code Matcher
A deterministic-first, retrieval-augmented LangGraph architecture for autonomous, air-gapped clinical ICD-10-CM coding from inpatient discharge summaries.
🏥 Production System Overview
Autonomous Clinical Medical Coding Architecture
🛡️ Strict UHDDS & HIPAA Validation Engine
👤 Author: Abhinav Gupta — AI Developer, AI India Innovations
📧 Email: abhinavg.aiindia@gmail.com
📦 Gitea Repository: Agentic-ICD-Code-Matcher
🌐 GitHub Mirror: Agentic_ICD_Code_Matcher
📑 Table of Contents
- 1. Executive Summary
- 2. Architectural Axioms & Medical Safety
- 3. End-to-End Workflow & Flowsheet Architecture
- 4. Technology Stack
- 5. Repository Architecture
- 6. Installation & Environment Setup
- 7. Dataset Ingestion & Offline Indexing
- 8. Running the Application
- 9. Concurrent Batch Processing (>= 10 PDFs)
- 10. Verification, Testing & Diagnostic Case Studies
- 11. Security & Data Privacy (HIPAA Compliance)
- 12. License
- 13. Author & Contact
1. Executive Summary
In clinical health systems, autonomous medical coding is high-stakes. Traditional approaches using generic generative Large Language Models (LLMs) suffer from severe flaws:
- Hallucinated Codes: Inventing plausible-looking ICD-10-CM codes that do not exist or violate billing rules.
- Over-Specificity & Upcoding: Defaulting to the most severe or granular diagnostic code without documentary evidence.
- Violation of UHDDS Rules: Inability to identify a single primary reason for admission versus chronic active comorbidities.
- Privacy Breaches: Transmitting Protected Health Information (PHI) to third-party cloud APIs.
Agentic ICD Code Matcher solves this by establishing a deterministic-first, dual-engine retrieval pipeline orchestrated with LangGraph:
- The LLM is strictly an NLP engine: It extracts clinical diagnoses with verbatim text evidence, assesses clinical context (negation, temporality, certainty, acuity), and ranks candidates. It is categorically banned from inventing or outputting ICD codes.
- The local CMS/CDC ICD-10-CM catalog is the sole source of truth: Only valid, terminal billable leaf codes can be selected.
- Deterministic Guardrails: 100% programmatic Python verification enforces catalog existence, HIPAA leaf specificity, Excludes1 mutual exclusions, 6 domain security firewalls, and the single-primary invariant.
- 100% Offline & Air-Gapped: Runs entirely locally via GPT4All (local GGUF weights), SentenceTransformers, and FAISS. Zero cloud egress.
2. Architectural Axioms & Medical Safety
| # | Medical Invariant | How It Is Strictly Enforced | Failure Action |
|---|---|---|---|
| 1 | No ICD Code Generation by LLM | The extraction prompt bans code generation. Model outputs only clinical conditions + verbatim documentary evidence. | Output filtered; only retrieved candidates considered. |
| 2 | Catalog Boundary Guarantee | Candidates retrieved via BM25 + FAISS are cross-checked against authoritative 83,319 local catalog. Non-existent codes are discarded. | Code purged from candidate pool. |
| 3 | Single Primary Diagnosis & UHDDS Precedence | Official UHDDS definition enforced: maximum ONE primary condition chiefly responsible for admission. Explicit provider primary designations take strict precedence over compound mentions or secondary clauses. | Multiple primary candidates demoted or disambiguated; compound clauses safely split. |
| 4 | Verbatim Evidence Provenance | Every code must link to an exact textual quote and character offsets from the clinical narrative. | Diagnosis without evidence is discarded. |
| 5 | Historical & Ruled-Out Exclusion | Negated ("denies", "no evidence of") and unmanaged historical PMH conditions are classified as EXCLUDED. |
Marked non-billable; omitted from coding submission. |
| 6 | Meta-Narrative & Cross-Reference Suppression | Chart navigation references ("see primary diagnosis for discussion", "refer to assessment above") and non-disease procedural notes are purged before candidate retrieval. | Filtered at clinical gate; prevented from polluting diagnostic candidates. |
| 7 | Terminal Leaf Specificity | Non-billable category headers (e.g. 3-character codes) are rejected; only terminal leaf nodes are valid. | Realigned to valid terminal code or abstained. |
| 8 | Mutual Excludes1 Detection | Pairs violating CDC Excludes1 guidelines cannot be co-billed. | Conflict flagged; lower priority code dropped or queried. |
| 9 | Nearest Relatable Match Guarantee | When documented evidence supports a confirmed diagnosis lacking an exact 1:1 database string entry, the closest verified billable code is assigned with status NEAREST_MATCH. |
Evidence preserved; tagged with visual badge & audit rationale. |
| 10 | Organism Protection & Equivalence | Genus-species abbreviations (E. coli, H. pylori, C. difficile, S. pneumoniae, MRSA) are shielded from sentence splitters and resolved against bracketed nomenclature [E. coli]. |
Organism integrity preserved without truncating names. |
| 11 | Auditable Abstention Engine | Whenever evidence is truly absent, ungrounded, or contradictory, the pipeline emits a structured AbstentionRecord. |
Explicit diagnostic abstention reasoning logged. |
3. End-to-End Workflow & Flowsheet Architecture
Production Clinical Architecture Flowsheet
Below is the production engineering architecture flowsheet illustrating the main pipeline flow, structured clinical concept reasoning, deterministic match constraints, disease family filtering, post-retrieval compatibility validation, domain firewalls, authoritative catalog indexing, and nearest relatable matching.
Figure 1: Production Clinical Diagnosis Extraction & ICD-10-CM Coding Architecture Flowsheet.
🔍 View Full-Resolution PNG Flowchart Diagram (3334x2396) • 📐 View Scalable Vector Graphics (SVG) Flowchart
Detailed Process Step Breakdown
The architecture executes an auditable, deterministic-first, 7-stage pipeline across 10 LangGraph nodes:
[Input Documents]
│
▼
[Stage 1: Ingestion & Boundary Detection] ──► (Nodes 1-2: validate_document, extract_text, SectionDetector)
│
▼
[Stage 2: Evidence Extraction & Shielding] ──► (Node 3: extract_diagnoses + Organism Protection)
│
▼
[Stage 3: Clinical Context & Management] ──► (Node 4: analyze_context: Negation, Temporality, Acuity, Management)
│
▼
[Stage 4: Concept Reasoning & MatchSpec] ──► (Node 5: classify_diagnoses + Hard Clinical Gate + Decomposition)
│
▼
[Stage 5: Multi-System Catalog Retrieval] ──► (Node 6: retrieve_candidates: 83,319 Catalog, FAISS + BM25)
│
▼
[Stage 6: Nearest Matching & Firewalls] ──► (Nodes 7-8: rank_candidates, Nearest Relatable Match, 6 Firewalls)
│
▼
[Stage 7: UHDDS Hierarchy & Finalization] ──► (Nodes 9-10: evaluate_confidence, finalize_output, SQLite WAL)
│
▼
[Validated CodingResult JSON & Streamlit UI]
-
Step 1: Document Ingestion & Verification (
validate_document):- Ingests inpatient discharge summaries and clinical notes in plain text or PDF format.
- Concurrency controlled via
BoundedDocumentGate(asyncio.Semaphore(10)). - Verifies payload integrity, non-zero file sizes, and valid text encodings. Unreadable payloads abort immediately to abstention records.
-
Step 2: Section Classification & Parsing (
extract_text):- Executes PyMuPDF off-thread (
asyncio.to_thread) to ensure non-blocking high-throughput extraction. - Detects scanned documents and flags for OCR processing.
- Employs
SectionDetectorto establish clinical section boundaries (History of Present Illness, Assessment & Plan, Hospital Course, Discharge Diagnoses, Past Medical History).
- Executes PyMuPDF off-thread (
-
Step 3: Clinical Evidence-First Extraction & Organism Shielding (
extract_diagnoses):- Local LLM extracts clinical diagnostic statements linked strictly to verbatim textual quotes and character offsets.
- Strict Zero-Hallucination Invariant: The LLM is banned from outputting ICD codes.
- Organism Shielding Engine: Genus-species nomenclature (
E. coli,H. pylori,C. difficile,S. pneumoniae,MRSA) is protected from sentence-splitting delimiters to prevent clinical entity corruption. - Broad duplicate mentions are deduplicated via clinical subsumption.
-
Step 4: Clinical Context & Assertion Analysis (
analyze_context):- Analyzes all extracted mentions across 4 orthogonal dimensions:
- Assertion:
AFFIRMATIVEvsNEGATED("denies chest pain", "no signs of bleeding"). - Temporality:
CURRENTvsHISTORICAL(inactive PMH) vsFAMILY_HISTORY. - Certainty:
CONFIRMEDvsSUSPECTEDvsRULED_OUT. - Acuity:
ACUTEvsCHRONICvsACUTE_ON_CHRONICvsUNSPECIFIED.
- Assertion:
- Confirms documented inpatient management, monitoring, evaluation, or active nursing care.
- Analyzes all extracted mentions across 4 orthogonal dimensions:
-
Step 5: Hard Clinical Gate & Compound Condition Decomposition (
classify_diagnoses):HardClinicalGatefilters out non-disease observations, chart navigation references ("see primary diagnosis for discussion"), and medication names.- Compound clauses (e.g., "Acute systolic heart failure with hypertensive emergency", "Calculus of gallbladder with acute cholecystitis") are partitioned into distinct, billable clinical conditions.
ClinicalConceptReasonerextracts anatomical qualifiers, laterality, histological attributes, and severity markers to construct structuredMatchSpecconstraints.
-
Step 6: Staged Retrieval across Authoritative 83,319 Multi-System Catalog (
retrieve_candidates):- Queries the pre-indexed database derived from
Database_1.xls/Database_2.xlsx:- ICD-10-CM: 72,204 diagnosis codes (A00–Z99).
- ICD-O: 3,347 oncology morphology codes.
- CPT: 13,722 surgical procedure and service codes.
- Disease family prefix filtering narrows candidate space by over
100\times. - Executes hybrid reciprocal rank fusion:
\text{Score}_{\text{hybrid}} = 0.6 \cdot \text{Score}_{\text{dense (FAISS FlatIP)}} + 0.4 \cdot \text{Score}_{\text{lexical (BM25Okapi)}}
- Queries the pre-indexed database derived from
-
Step 7: Nearest Relatable Match Engine & 6 Security Firewalls (
rank_candidates&validate_codes):- Nearest Relatable Match Engine: If a confirmed, well-evidenced diagnosis lacks an exact 1:1 database string entry, the pipeline retrieves and assigns the closest relatable verified billable code (
matching_status="NEAREST_MATCH"). Documentary quotes and offsets are preserved, eliminating blank diagnosis fields. - Pure Abstention Path: When clinical documentation is truly absent, negated, or contradictory, the system emits an auditable
AbstentionRecord. - 6 Domain Security Firewalls: 100% programmatic validation strictly enforces CPT, Medication, Procedure, Attribute, Negation, and Specificity Firewalls, leaf billability, and Excludes1 mutual exclusions.
- Nearest Relatable Match Engine: If a confirmed, well-evidenced diagnosis lacks an exact 1:1 database string entry, the pipeline retrieves and assigns the closest relatable verified billable code (
-
Step 8: UHDDS Hierarchy Enforcement & Final Payload (
finalize_output):- Enforces official Uniform Hospital Discharge Data Set (UHDDS) rules: Rank 1 is strictly Primary, and all remaining valid active conditions are Secondary.
- Formulates terminal Pydantic
CodingResultschema omitting internal LLM prompts. - Commits encounter records and audit trail into SQLite with Write-Ahead Logging (WAL).
- Renders interactive clinical cards with
Nearest Relatable Matchbadges in the Streamlit UI.
Core Security & Domain Firewalls
The architecture strictly enforces 6 non-negotiable medical coding firewalls to prevent candidate pollution and hallucination:
- CPT Firewall: Segregates the 13,722 CPT procedure codes from the 72,204 ICD diagnosis codes. Surgical procedures (e.g., mastectomy, endoscopy, ACL reconstruction) can never become ICD disease diagnoses.
- Medication Firewall: Prescriptions and medications (e.g., Cremaffin for constipation, insulin, bronchodilators) may corroborate active clinical management, but can never create a new diagnosis candidate.
- Procedure Firewall: Surgical mentions support encounter status and treatment intensity, but cannot be classified as primary diagnoses.
- Attribute Firewall: Biomarkers, histological grades, receptor statuses (e.g., ER/PR/HER2, Ki67, Stage IV, displacement status) are captured as concept qualifiers and cannot become independent diagnostic codes.
- Negation Firewall: Explicitly ruled-out ("no evidence of", "denies", "negative for") and unmanaged historical PMH conditions are routed to auditable
AbstentionRecordentries. - Specificity Firewall: Strictly enforces the invariant
\text{CODE\_SPECIFICITY} \le \text{EVIDENCE\_SPECIFICITY}. Over-specific candidates (e.g., displaced fractures when displacement is undocumented) are penalized, realigned, or abstained.
Interactive State Graph (Mermaid)
The LangGraph workflow orchestrates evidence extraction, concept reasoning, match constraints, and staged database retrieval:
flowchart TD
classDef llm fill:#f3e8ff,stroke:#9333ea,stroke-width:2px,color:#1e1b4b;
classDef det fill:#ecfdf5,stroke:#059669,stroke-width:2px,color:#064e3b;
classDef ret fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#082f49;
classDef gate fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f;
classDef firewall fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d;
classDef nearest fill:#ffedd5,stroke:#ea580c,stroke-width:2px,color:#9a3412;
DOC[Clinical Document PDF / Text] --> PARSER[Document Parser]:::det
PARSER --> SEC[Section Classifier & Boundaries]:::det
SEC --> EXTRACT[Clinical Evidence Extraction + Organism Shield]:::llm
EXTRACT --> ASSERT[Assertion & Temporality Analysis]:::det
ASSERT --> GATE{Hard Clinical Gate}:::gate
GATE -- Non-disease / Ruled-out --> ABSTAIN[Pure Abstention Record]:::firewall
GATE -- Valid Disease Entity --> NORM[Normalization & Compound Decomposition]:::det
NORM --> ATTR[Clinical Concept Reasoner & Attributes]:::det
ATTR --> MATCH_SPEC[MatchSpec Builder]:::det
subgraph Database_Layer [Authoritative Multi-System Catalog]
DB[(83,319 Verified Records: ICD-10-CM, ICD-O, CPT)]
INDEX[Prefix Map, BM25 Index, FAISS Vectors]
DB --> INDEX
end
MATCH_SPEC --> FAM_FILTER[Disease Family Prefix Filter]:::ret
INDEX --> FAM_FILTER
FAM_FILTER --> RETRIEVE[Staged BM25 & FAISS Hybrid Retrieval]:::ret
RETRIEVE --> COMPAT[Compatibility Reasoner & 6 Firewalls]:::det
COMPAT -- Unsupported / Excludes1 --> ABSTAIN
COMPAT -- Unindexed Term + Evidence --> NEAREST[Nearest Relatable Match Engine]:::nearest
COMPAT -- Exact Billable Match --> RANK[Candidate Ranking Agent]:::det
NEAREST --> VALIDATE[Deterministic Validation & Leaf Check]:::gate
RANK --> VALIDATE
VALIDATE --> PRIMARY_SEC[UHDDS Classifier: Rank 1 Primary, Rest Secondary]:::det
PRIMARY_SEC --> CONSISTENCY[Final Consistency Validator]:::gate
CONSISTENCY --> JSON_OUT[Structured JSON Response & UI Cards]:::det
Detailed 10-Node Execution Breakdown
Phase 1: Ingestion & Document Verification
- Input Gateway: Clinical documents arrive as plain text or
.pdfdischarge summaries. Concurrent ingestion of\ge 10documents is managed viaBoundedDocumentGate(asyncio.Semaphore(10)). - Node 1 (
validate_document): Validates payload structure, checks file existence and non-zero byte size. Unreadable inputs short-circuit directly to the abstention engine. - Node 2 (
extract_text): PyMuPDF extraction executed off-thread (asyncio.to_thread) to prevent event-loop blocking. EmploysSectionDetectorto parse clinical sections (History of Present Illness, Assessment & Plan, Hospital Course, Discharge Diagnoses) and normalizes whitespace while capturing character spans.
Phase 2: Clinical Language Understanding & UHDDS Context
- Node 3 (
extract_diagnoses): A local LLM extracts diagnostic entities. Core Constraint: Must provide exact verbatim quotes and offsets from the text. The model is strictly prohibited from inventing or assigning ICD codes. Clinical condition subsumption removes broad duplicate mentions. - Node 4 (
analyze_context): Evaluates diagnostic mentions across 4 axes:- Negation:
AFFIRMATIVEvsNEGATED("denies chest pain", "ruled out"). - Temporality:
CURRENTvsHISTORICAL(PMH) vsFAMILY_HISTORY. - Certainty:
CONFIRMEDvsSUSPECTEDvsRULED_OUT. - Acuity:
ACUTEvsCHRONICvsACUTE_ON_CHRONICvsUNSPECIFIED.
- Negation:
- Node 5 (
classify_diagnoses): Enforces official Uniform Hospital Discharge Data Set (UHDDS) rules:- Single Primary Anchor: Designates at most ONE Primary Diagnosis (chief reason for admission). Explicit provider headers (
PRIMARY DIAGNOSIS:,PRINCIPAL:,1. Primary:) strictly take precedence over narrative mentions or secondary lists. - Compound Clause Disambiguation: For compound diagnoses (e.g.,
PRIMARY: Acute Systolic Heart Failure with Hypertensive Emergency), the anchor entity is preserved as Primary while trailing clauses are partitioned as Secondary. - Secondary Comorbidities: Active co-existing conditions receiving inpatient monitoring, evaluation, or therapy are designated as Secondary.
- Exclusion & Meta-Purging: Historical conditions without active inpatient monitoring/treatment and chart navigation meta-narratives (e.g., "see primary diagnosis for discussion") are classified as
EXCLUDED.
- Single Primary Anchor: Designates at most ONE Primary Diagnosis (chief reason for admission). Explicit provider headers (
Phase 3: Dual-Engine Retrieval & Pool-Constrained Ranking
- Node 6 (
retrieve_candidates): Queries the authoritative local 83,319-record multi-system catalog (Database_2.xlsx: 72,204 ICD-10-CM, 3,347 ICD-O, 13,722 CPT):- Lexical Search (BM25Okapi): Keyword matching against official descriptions and clinical synonyms.
- Semantic Dense Search (FAISS FlatIP): Cosine similarity over 384-dimensional vector embeddings generated by local sentence transformers.
- Hybrid Fusion: Computes composite rank using Reciprocal Rank Fusion (RRF) and weighted scoring:
\text{Score}_{\text{hybrid}} = 0.6 \cdot \text{Score}_{\text{dense}} + 0.4 \cdot \text{Score}_{\text{lexical}} - Catalog Boundary Filter: Purges any candidate not strictly in the local catalog.
- Node 7 (
rank_candidates): Evaluates retrieved candidate codes against verbatim clinical evidence:- Constrained Pool Invariant: The ranker can select only from the top-
Kretrieved candidates. - Nearest Relatable Match Engine: If confirmed documentary evidence exists for a condition lacking an exact 1:1 database string entry, the pipeline assigns the closest verified billable code with
matching_status="NEAREST_MATCH", preventing valid clinical diagnoses from being dropped.
- Constrained Pool Invariant: The ranker can select only from the top-
Phase 4: Deterministic Guardrails, Abstention & Storage
- Node 8 (
validate_codes): A 100% programmatic Python engine (non-LLM) verifying:- 6 Domain Firewalls: CPT Firewall, Medication Firewall, Procedure Firewall, Attribute Firewall, Negation Firewall, and Specificity Firewall.
- Catalog Existence & Leaf Billability: Verifies code is a terminal billable leaf node.
- Excludes1 Rules: Detects and prevents co-billing of mutually exclusive conditions.
- Anti-Hallucination Specificity: Demotes overly specific codes unsupported by text.
- Node 9 (
evaluate_confidence): Computes composite confidence scores across extraction, retrieval, and ranking. Routes ungrounded or contradictory mentions to auditableAbstentionRecordentries. - Node 10 (
finalize_output): Enforces UHDDS primary sequencing (Rank 1 strictly Primary, remaining valid diagnoses Secondary), compiles the terminal PydanticCodingResultschema, archives the encounter into SQLite with WAL mode, and renders results withNearest Relatable Matchbadges.
4. Technology Stack
| Category | Component / Tool | Version / Specification | Technical Role & Invariants |
|---|---|---|---|
| Language | Python | 3.13.13 |
Modern typing, asyncio concurrency, zero-GIL preparation |
| Workflow Engine | LangGraph | >=0.2.0 |
10-node state graph, conditional edges, error short-circuiting |
| Local LLM Layer | GPT4All / llama.cpp | Local GGUF (e.g. Mistral-7B-Instruct) | Offline inference, allow_download=False, thread-safe singleton lock |
| Embeddings | SentenceTransformers | BGE-Small-EN / FastLocal | 384-dim dense vectors, 100% local, cosine similarity |
| Vector Retrieval | FAISS | faiss-cpu (FlatIP) |
High-speed dense similarity search over ICD descriptions |
| Lexical Retrieval | rank-bm25 | BM25Okapi |
Fast inverted index keyword matching & inclusion terms |
| PDF Extraction | PyMuPDF (fitz) | >=1.24.0 |
High-fidelity text extraction, section segmentation, OCR detection |
| Web Interface | Streamlit | >=1.38.0 |
Clinical workspace, batch PDF uploader, SQLite vault browser |
| REST Service | FastAPI | >=0.112.0 |
Non-blocking async endpoints, OpenAPI/Swagger documentation |
| Persistence | SQLite + SQLAlchemy | WAL (Write-Ahead Logging) | Thread-safe, transaction-isolated clinical encounter vault |
| Schema Validation | Pydantic | v2.x |
Strict typing, runtime invariant checking, serialization |
| Quality & Tests | Pytest & Ruff | 199 Tests (100% Passed) | Comprehensive regression, adversarial, unit & e2e coverage across 33 test suites |
5. Repository Architecture
Agentic_ICD_Code_Matcher/
├── .env.example # Environment variables configuration template
├── .gitignore # Git rules (virtualenvs, models, SQLite databases)
├── pyproject.toml # Project specification, dependencies, ruff/pytest configs
├── README.md # Comprehensive architecture & operational documentation
├── requirements.txt # Locked Python package dependencies
├── app.py # Streamlit clinical workspace entrypoint
├── diagnostic_pipeline_report.json # Benchmark evaluation results across clinical test cases
│
├── Database/ # Authoritative multi-system clinical catalogs (83,319 records)
│ ├── Database_1.xls # Binary BIFF8 workbook export
│ └── Database_2.xlsx # OpenXML multi-sheet workbook (ICD-10-CM, ICD-O, CPT)
│
├── data/
│ ├── icd10/ # CMS/CDC ICD-10-CM source files & sample test dataset
│ │ ├── .gitkeep
│ │ └── sample_hospital_icd.csv # Pre-bundled verified sample dataset
│ ├── indexes/ # Persisted FAISS and BM25 offline index artifacts
│ │ ├── .gitkeep
│ │ ├── bm25_index.pkl # Pre-indexed BM25 token cache
│ │ ├── faiss.index # FAISS vector index
│ │ ├── faiss_records.json # Indexed record mappings
│ │ ├── icd_catalog.json # Pre-built authoritative catalog metadata
│ │ └── index_stats.json # Indexing telemetry and count
│ └── samples/ # Sample clinical discharge summary PDFs and texts
│
├── docs/
│ └── assets/ # Vector and high-resolution architecture diagrams
│ ├── workflow_flowsheet.jpg # Production architecture flowsheet diagram
│ ├── workflow_flowchart.png # Ultra-crisp high-resolution PNG diagram (3334x2396)
│ └── workflow_flowchart.svg # Scalable vector graphics (SVG) diagram
│
├── models/ # Local offline model weights storage
│ ├── embeddings/ # SentenceTransformer model files
│ └── gguf/ # Quantized GGUF LLM weights (e.g. Mistral-7B)
│
├── scripts/ # Utility & indexing CLI scripts
│ ├── generate_flowchart.py # SVG & high-res PNG flowchart generator (PyMuPDF)
│ ├── index_icd.py # CLI pipeline to ingest & index ICD datasets
│ └── run_pipeline_diagnostic_report.py # Automated end-to-end benchmark evaluator
│
├── src/medical_coding/ # Core source package
│ ├── agents/ # Specialized clinical reasoning & ranking agents
│ ├── api/ # FastAPI application, dependency injection, routes
│ ├── config/ # Typed Pydantic Settings & environment manager
│ ├── database/ # SQLite models, repository, WAL connection manager
│ ├── dataset/ # CMS order file loaders & LocalICDCatalog engine
│ ├── graph/ # LangGraph 10-node workflow, states, and transitions
│ ├── ingestion/ # Multimodal document extractors (PDF, Text, RapidOCR)
│ ├── models/ # Local model wrappers, lifecycle singleton, lock manager
│ ├── orchestration/ # MedicalCodingPipeline async pipeline driver
│ ├── pdf/ # PyMuPDF extractor & concurrent BatchPDFProcessor
│ ├── prompts/ # Strict system prompts with evidence & boundary constraints
│ ├── reasoning/ # ClinicalConceptReasoner, MatchSpecBuilder, CompatibilityReasoner
│ ├── retrieval/ # BM25 lexical, FAISS dense, and Hybrid RRF retrievers
│ ├── schemas/ # Pydantic domain models, state schemas, API payloads
│ ├── ui/ # Streamlit clinical workspace components & pages
│ ├── utils/ # Logging, string matching, ICD format helpers
│ └── validation/ # Deterministic rules, reverse attribute checker & 6 firewalls
│
└── tests/ # 199 Unit, Integration, Adversarial & Regression Tests (100% Passed)
├── test_adversarial_suite.py # Prompt injection, noise & fuzzing tests
├── test_api.py # FastAPI REST service & endpoint tests
├── test_candidate_ranking.py # Hybrid ranking & score verification tests
├── test_classification.py # UHDDS primary vs secondary classification tests
├── test_clinical_extraction.py # Verbatim quote & evidence extraction tests
├── test_config.py # Environment configuration tests
├── test_context_assessment.py # Assertion, temporality & acuity tests
├── test_database.py # SQLite transaction & audit persistence tests
├── test_end_to_end_pipeline.py # Full 10-node pipeline integration tests
├── test_ent_multidiagnosis_e2e.py # Complex ENT multi-diagnosis cases
├── test_five_areas_regression.py # 5-area regression matrix tests
├── test_full_regression_matrix.py # Multi-condition inpatient clinical cases
├── test_generalized_multi_condition_cases.py # Multi-condition clinical scenarios
├── test_generalized_reasoning_adversarial.py # Adversarial non-clinical noise filtering
├── test_graph.py # LangGraph state machine compilation tests
├── test_icd_matching_regression.py # Authoritative database code regressions & UI rendering tests
├── test_imports.py # Zero circular dependency checks
├── test_ingestion.py # Dataset loader & catalog integrity tests
├── test_llm_infrastructure.py # Offline model lifecycle & inference locking tests
├── test_multimodal_e2e.py # Plaintext + PDF multimodal verification tests
├── test_multisystem_and_secondary_completeness.py # Multisystem secondary completeness
├── test_multisystem_database.py # Multi-system ICD-10-CM, ICD-O & CPT catalog matching
├── test_pdf_processing.py # PyMuPDF & concurrency semaphore tests
├── test_pipeline_persistence.py # SQLite encounter & session persistence tests
├── test_primary_fix_ranking.py # Strict Rank 1 primary and secondary ranking
├── test_retrieval.py # BM25, FAISS, and hybrid RRF tests
├── test_schemas.py # Pydantic schema validation tests
├── test_state.py # State transitions & execution snapshot tests
├── test_surgical_oncology_repair.py # Surgical oncology & procedure firewall tests
├── test_user_note_e2e.py # End-to-end user clinical notes verification
└── test_validation.py # Deterministic rule & Excludes1 tests
6. Installation & Environment Setup
📥 Clone Repository
# Clone from Gitea
git clone https://gitea.aiindia.ai/Abhinav_Gupta/Agentic-ICD-Code-Matcher.git
cd Agentic-ICD-Code-Matcher
🚀 Automated Quick-Start Installers (Windows & Linux)
The repository provides cross-platform installer scripts that automate the entire setup:
- Creates a clean Python virtual environment (
env) - Upgrades
pip,setuptools, andwheel - Installs all dependencies from
requirements.txt - Configures
.envfrom.env.example - Detects the local
Database/folder (ICD-10-CM, ICD-O, CPT) and builds/verifies FAISS & BM25 search indexes
Important
Strict Separation of Concerns: The installer scripts only install and configure the environment. They do not start the application. Use the dedicated runner scripts to start the app.
Windows (Batch or PowerShell):
:: Using Command Prompt (Batch)
install.bat
or
# Using PowerShell
.\install.ps1
Linux / macOS:
chmod +x install.sh run.sh
./install.sh
🏃 Dedicated Runners (Windows & Linux)
Once installed, use the runner script to start the interface:
Windows:
:: Launch Streamlit Web UI (Default)
run.bat
:: Or launch in PowerShell
.\run.ps1
:: Launch FastAPI REST Service
run.bat --api
:: Or in PowerShell: .\run.ps1 -Api
Linux / macOS:
:: Launch Streamlit Web UI
./run.sh
:: Launch FastAPI REST Service
./run.sh --api
Manual Setup (Alternative)
# Clone the repository
git clone https://github.com/AbhinavEliac/Agentic_ICD_Code_Matcher.git
cd Agentic_ICD_Code_Matcher
# Create virtual environment
python -m venv env
# Activate (Windows)
.\env\Scripts\activate
# Activate (Linux/macOS)
source env/bin/activate
# Install dependencies
pip install --upgrade pip setuptools wheel
pip install -r requirements.txt
# Copy environment template
cp .env.example .env
7. Local Database & Authoritative Multi-System Matching
The engine performs zero-hallucination vector and semantic matching against authoritative medical coding workbooks located in the local Database/ directory (Database_1.xls / Database_2.xlsx):
- ICD-10-CM: 74,700+ authoritative clinical diagnosis codes
- ICD-O: 800+ oncology / morphology codes (
^M[89][0-9]{3}) - CPT: 7,700+ current procedural terminology codes
- Privacy & Security: The
Database/directory is strictly kept in local storage and is ignored in version control (.gitignore) with zero remote exposure.
Standardized Structured JSON Output Format
For every matched condition, the engine outputs deterministic structured JSON adhering strictly to:
{
"description": "Acute systolic (congestive) heart failure",
"role": "PRIMARY",
"acuity": "ACUTE",
"certainty": "CONFIRMED",
"evidence_quote": "Patient presented with acute decompensated systolic heart failure.",
"confidence_score": 0.96,
"is_terminal_billable": true,
"icd10cm": "I50.21",
"icdo": null,
"cpt": null
}
If an oncology morphology or procedure is matched, the corresponding icdo or cpt field is populated with the authoritative local code (or null if not matched):
{
"description": "Malignant neoplasm of unspecified site of right female breast",
"role": "PRIMARY",
"acuity": "UNSPECIFIED",
"certainty": "CONFIRMED",
"evidence_quote": "Biopsy confirmed right breast infiltrating duct carcinoma.",
"confidence_score": 0.94,
"is_terminal_billable": true,
"icd10cm": "C50.911",
"icdo": "M8500.3",
"cpt": "19120"
}
Building & Re-indexing Search Indexes
python scripts/index_icd.py --force-fast-embeddings
The indexing script automatically checks for Database/Database_2.xlsx, ingests all sheets, and serializes the BM25 and FAISS vector index artifacts directly into data/indexes/.
8. Running the Application
Clinical Streamlit Dashboard
Launch the interactive clinical interface:
streamlit run app.py
Open your browser to http://localhost:8501.
Core UI Features:
- 🩺 Clinical Coding Workspace:
- Ingest PDF discharge summaries or paste clinical notes.
- Pre-loaded with realistic clinical scenarios (Acute Systolic Heart Failure, STEMI, COPD with Pneumonia, Sepsis with AKI, Negation/Rule-Out demonstration).
- Generates and downloads synthetic clinical PDFs for testing.
- Clinical Decision Cards: Displays Primary Diagnosis in bold, billable status, confidence score, acuity, certainty, and highlighted verbatim evidence quotes with sanitized CommonMark-safe HTML rendering (preventing raw markdown code block spills) and responsive layout.
- Audit Trail: Real-time non-LLM checks confirming catalog existence, leaf specificity, and Excludes1 non-contradiction.
- 📑 Concurrent Batch PDF Ingestion:
- Upload and process
\ge 10clinical PDFs simultaneously with live status tracking and CSV export.
- Upload and process
- 🗄️ Database & Encounters Vault:
- Real-time search by encounter ID, ICD code, or clinical keywords.
- Filter by status (
SUCCESS,PARTIAL_SUCCESS,ABSTAINED,ERROR) and billable status. - Vault export to CSV and JSON.
- 📊 Clinical Quality Analytics:
- Key KPIs: Total encounters, total diagnoses, HIPAA billable ratio, and mean processing latency.
- Interactive charts of top primary diagnoses and secondary comorbidities.
- 🔍 ICD-10 Catalog & Semantic Explorer:
- Test lexical and semantic retrieval live against the local catalog.
FastAPI REST API
Start the high-performance async REST service:
uvicorn src.medical_coding.api.app:create_app --factory --host 0.0.0.0 --port 8000 --reload
Interactive Swagger documentation is available at http://localhost:8000/docs.
Endpoints:
| Method | Endpoint | Description |
|---|---|---|
GET |
/health |
Service health status and catalog readiness |
POST |
/api/v1/code/text |
Asynchronous clinical text coding |
POST |
/api/v1/code/pdf |
Upload and code a single clinical PDF document |
POST |
/api/v1/code/batch-pdf |
Multi-file concurrent upload (\ge 10 PDFs) |
9. Concurrent Batch Processing (>= 10 PDFs)
The system handles concurrent document processing through BatchPDFProcessor:
- CPU Offloading: Text extraction via PyMuPDF runs in thread pools (
asyncio.to_thread), preventing event-loop stalling. - Controlled Concurrency: Regulated via
asyncio.Semaphore(max_concurrency=10), ensuring system stability under heavy multi-document load. - Inference Serialization: CPU inference on local GGUF weights is serialized via
LLMLifecycleManagerto avoid memory context corruption inllama.cpp. - Fault Isolation: Errors in individual PDFs are caught and recorded as
ExecutionStatus.ERRORorABSTAINED, ensuring that corrupted files never crash the entire batch.
10. Verification, Testing & Diagnostic Case Studies
Running the Test Suite
The repository includes 199 unit, integration, adversarial, and full clinical regression tests covering all modules with a 100% pass rate:
pytest -v
Output:
============================= test session starts =============================
platform win32 -- Python 3.13.13, pytest-9.1.1, pluggy-1.6.0
collected 199 items
tests/test_adversarial_suite.py ...... [ 3%]
tests/test_api.py .... [ 5%]
tests/test_candidate_ranking.py ......... [ 10%]
tests/test_classification.py .......... [ 15%]
tests/test_clinical_extraction.py .......... [ 20%]
tests/test_config.py ... [ 22%]
tests/test_context_assessment.py ............. [ 28%]
tests/test_database.py ..... [ 31%]
tests/test_end_to_end_pipeline.py ........ [ 35%]
tests/test_ent_multidiagnosis_e2e.py .. [ 36%]
tests/test_five_areas_regression.py ........... [ 41%]
tests/test_full_regression_matrix.py ........... [ 47%]
tests/test_generalized_multi_condition_cases.py ... [ 48%]
tests/test_generalized_reasoning_adversarial.py ........ [ 52%]
tests/test_graph.py .. [ 53%]
tests/test_icd_matching_regression.py ........... [ 59%]
tests/test_imports.py . [ 60%]
tests/test_ingestion.py ...... [ 63%]
tests/test_llm_infrastructure.py ......... [ 67%]
tests/test_multimodal_e2e.py .... [ 69%]
tests/test_multisystem_and_secondary_completeness.py ... [ 71%]
tests/test_multisystem_database.py .. [ 72%]
tests/test_pdf_processing.py ........... [ 77%]
tests/test_pipeline_persistence.py ... [ 79%]
tests/test_primary_fix_ranking.py .... [ 81%]
tests/test_retrieval.py .............. [ 88%]
tests/test_schemas.py ... [ 89%]
tests/test_state.py .... [ 91%]
tests/test_surgical_oncology_repair.py ...... [ 94%]
tests/test_user_note_e2e.py . [ 95%]
tests/test_validation.py .... [100%]
============================ 199 passed in 58.42s =============================
Code Quality & Linting
Enforced using Ruff:
ruff check src tests app.py
Diagnostic Evaluation Cases
Execute the automated diagnostic evaluation across real-world clinical admission cases:
python scripts/run_pipeline_diagnostic_report.py
This generates diagnostic_pipeline_report.json evaluating:
- CASE 1: Comprehensive Inpatient Admission (Acute Systolic HF
I50.21, T2DME11.9, HTNI10). - CASE 2: Acute Myocardial Infarction with Excludes1 Conflict resolution.
- CASE 3: COPD Exacerbation with Secondary Community-Acquired Pneumonia.
- CASE 4: Severe Sepsis with Acute Kidney Injury (UHDDS primary sequencing).
- CASE 5: Negation and Ruled-Out Deep Vein Thrombosis (verification of zero false positives).
- CASE 6: Specificity Invariant (demoting unspecified mentions when granular evidence is absent).
11. Security & Data Privacy (HIPAA Compliance)
This system is engineered for compliance with the Health Insurance Portability and Accountability Act (HIPAA) and institutional data governance:
- 100% Air-Gapped: Runs entirely offline with zero external network connectivity.
- Zero Cloud API Egress: No clinical narratives or PHI are transmitted to external endpoints (OpenAI, Anthropic, Google, etc.).
- Local Weight Enforcement: Model wrappers enforce
allow_download=Falseat runtime. - Transaction-Isolated Persistence: Local SQLite database operates with Write-Ahead Logging (WAL) and strict character offset audit trails.
12. License
Distributed under the MIT License. See LICENSE for details.
13. Author & Contact
Abhinav Gupta
AI Developer, AI India Innovations
- 📧 Email: abhinavg.aiindia@gmail.com
- 🏢 Organization: AI India Innovations
- 🐙 GitHub: @AbhinavEliac
- 📦 Gitea Repository: Agentic-ICD-Code-Matcher
- 🔄 GitHub Mirror: Agentic_ICD_Code_Matcher
Autonomous Clinical ICD-10-CM Medical Coding Engine
Deterministic-First, Dual-Engine Retrieval & LangGraph Orchestration