Executive Summary (TL;DR)
Aether Anesthesia Calculator is a mission-critical mobile application built for zero-latency, high-reliability clinical environments (operating rooms, pediatric ICUs, and trauma bays). This article details the software architecture behind Aether:
- Data Architecture: Replaced risky cloud API queries with a hybrid offline-first asset bundle (
drugs_enriched_v2.json) compiled into Flutter assets for microsecond synchronous reads and 100% offline operation.- Data Pipeline: Engineered an out-of-band Python pipeline utilizing cascading domain-restricted web scraping (DuckDuckGo), DeepSeek LLM extraction, and strict Pydantic schema validation to ingest, normalize, and audit peer-reviewed medical data with zero hallucination.
- Reactive Math Engine: Implemented a lightweight Provider +
ChangeNotifierstate system in Flutter that re-calculates complex physiological formulas (Devine IBW, Mosteller BSA, Mapleson MAC, Holliday-Segar 4-2-1, Modified Cole ETT) in under 0.1ms without UI lag.- Opioid Equianalgesic Converter: Built a unit-normalized cross-tolerance conversion engine paired with embedded dynamic WebViews for instant bedside citation verification.
Table of Contents
- Introduction: Engineering for Zero-Tolerance Clinical Environments
- Evaluating Data Architecture Options: Cloud APIs vs. Local Asset Bundles
- Data Sourcing & Pipelines: Domain Scraping, LLMs, and Pydantic Validation
- Flutter State Engine: Reactive Math & Physiological Calculations
- Opioid Equianalgesic Converter: Math Engine & Embedded Verification
- Platform Optimizations & Android API 36 Compliance
- Summary Matrix of Architectural Trade-Offs
- Building Compliance-Critical Software with Blackspring
1. Introduction: Engineering for Zero-Tolerance Clinical Environments
Building software for clinical healthcare—particularly perioperative anesthesia and intensive care—presents engineering constraints fundamentally different from standard consumer applications. In an operating room during a pediatric intubation emergency or a sudden hypotensive crisis, there is zero tolerance for data latency, calculation rounding errors, UI lag, or unverified clinical citations.
A single mistake in drug dosage calculation or unit conversion can have severe patient outcomes. For instance:
- A pediatric patient requiring rapid sequence induction (RSI) requires weight- and age-adjusted dosages accurate to the microgram.
- Operating suites are often located in hospital basements or heavily shielded rooms where cellular signals fluctuate or fail entirely.
Aether Anesthesia Calculator was engineered to eliminate these failure points. This technical post presents an architectural deep-dive into how we designed and built Aether using Flutter for the mobile interface and Python for the data pipeline. We detail how we evaluated competing data storage strategies, constructed automated LLM-assisted verification pipelines enforced by Pydantic schemas, and built a sub-millisecond offline state engine.
2. Evaluating Data Architecture Options: Cloud APIs vs. Local Asset Bundles
The foundational architectural decision in building Aether was determining how clinical drug data, opioid conversion factors, and physiological reference baselines should be stored, served, and updated.
| Data Architecture Option | Read Latency | Offline Reliability | Maintainability | Auditability |
|---|---|---|---|---|
| Option A: Cloud API (REST/GraphQL) | High (200–1500ms) | Low (Fails without signal) | High | Medium |
| Option B: Hardcoded Code Constants | Zero (<0.01ms) | High (100% offline) | Extremely Low | Poor |
| Option C: Hybrid Offline Asset Bundle (Selected) | Microsecond (<0.1ms) | High (100% offline) | High (Automated Pipeline) | Excellent (Git Versioned) |
Detailed Option Evaluation
Option A: Cloud Database with REST or GraphQL APIs
Under this conventional cloud web architecture, drug data and calculation parameters reside in a remote cloud database (such as Firebase Firestore or PostgreSQL). The client application fetches updated clinical parameters via network API requests.
- Evaluation: While Cloud APIs enable instant remote updates without requiring App Store reviews, this model introduces an unacceptably high point of failure in perioperative environments. Operating suites, ICUs, and trauma bays are frequently situated in basement floors or surrounded by heavy structural shielding. Cellular connectivity and hospital Wi-Fi in these spaces are notoriously spotty or non-existent. A network timeout during emergency dosage verification is unacceptable. Furthermore, network round-trips add 200ms to 1500ms of latency.
Option B: Hardcoded Application Constants
In this approach, all drug definitions, dosing ranges, and conversion factors are hardcoded directly into client Dart source files as static maps or constant data classes.
- Evaluation: Hardcoded constants deliver 100% offline availability and instant execution. However, this creates a severe maintenance bottleneck. Application logic becomes tightly coupled with clinical data content, making schema updates difficult and auditing data provenance across hundreds of drug parameters highly error-prone.
Option C (Selected): Hybrid Offline-First Asset Bundle with Automated Out-of-Band Data Engineering
We engineered a hybrid offline-first architecture where structured JSON datasets (drugs_enriched_v2.json, opioid_factors.json, and vitals_baselines.json) are programmatically compiled, validated, and bundled directly into the Flutter application package assets (assets/data/).
┌────────────────────────────────────────────────────────┐
│ Out-of-Band Python Pipeline │
│ PDF Manuals ──► DDGS Scraping ──► DeepSeek ──► Pydantic│
└───────────────────────────┬────────────────────────────┘
│ (Compiles JSON)
▼
┌────────────────────────────────────────────────────────┐
│ Flutter Asset Bundle (Offline) │
│ assets/data/drugs_enriched_v2.json │
│ assets/data/opioid_factors.json │
└───────────────────────────┬────────────────────────────┘
│ (Synchronous Read)
▼
┌────────────────────────────────────────────────────────┐
│ Microsecond State Engine │
│ PatientState (ChangeNotifier) ──► Instant UI Refresh │
└────────────────────────────────────────────────────────┘
Key Technical Advantages of Selected Architecture:
- Zero Network Dependency: Every calculation, drug lookup, and reference protocol executes completely offline without issuing a single network packet.
- Microsecond Data Access: Bundled JSON assets are parsed into memory during app initialization, allowing instantaneous, synchronous queries.
- Version Control & Auditability: The clinical dataset is committed and version-controlled in Git alongside application code, guaranteeing 100% reproducibility across releases.
- Decoupled Data Engineering: Data ingestion, scraping, and validation are shifted entirely to an out-of-band Python pipeline in the backend repository, keeping the runtime client lightweight and secure.
3. Data Sourcing & Pipelines: Domain Scraping, LLMs, and Pydantic Validation
Sourcing accurate, peer-reviewed medical parameters for over 100 anesthesia medications requires moving beyond manual data entry, which is susceptible to human transposition errors (such as misreading 0.05 mg/kg as 0.5 mg/kg).
┌─────────────────┐ ┌─────────────────────────┐ ┌─────────────────────────┐
│ Stage 1: Ingest │ ───► │ Stage 2: Scrape Domains │ ───► │ Stage 3: LLM & Pydantic │
│ PDF Manuals │ │ (site:nih.gov, asahq) │ │ (DeepSeek + Validation) │
└─────────────────┘ └─────────────────────────┘ └─────────────────────────┘
Data Pipeline Architecture Evaluation
Option 1: Manual Input & Spreadsheet Editing
Initial tests curating clinical data via manual CSV entries exposed severe scalability bottlenecks. Formatting inconsistent text notes, verifying unit consistency across routes, and mapping peer-reviewed URL citations proved slow and prone to formatting drift.
Option 2: Unfiltered Web Search Scraping
We evaluated automated web scrapers using unconstrained search queries to fetch missing clinical parameters. However, unconstrained web searches index commercial blogs, online forums, and unverified summaries that lack peer-reviewed authority.
Option 3 (Selected): Multi-Stage Automated Python Pipeline with Cascading Domain Targeting, LLM Anti-Hallucination, and Pydantic Schema Enforcement
To achieve automated scalability with absolute clinical precision, we engineered a three-stage data pipeline using Python (scripts/generate_karthik_json.py, scripts/enrich_drugs.py, and scripts/combine_and_validate_drugs.py).
Pipeline Technical Implementation Walkthrough
Stage 1: PDF Ingestion and Regex Normalization
Raw clinical data was ingested from authoritative reference manuals, including the KarthikMD OT ICU Drug Reference by Dr. Karthik Deegutla (citing SSC 2026, AHA 2025, DAS 2025, and ASA 2022 guidelines). Python scripts extracted raw text and used regular expressions to parse dosage strings, indications, side effects, and administration routes into a normalized intermediate JSON schema (drugs_karthik_md.json).
Stage 2: Cascading Domain-Restricted Web Scraping
To enrich each drug entry with exact pharmacokinetic/pharmacodynamic (PK/PD) profiles, hard maximum safe dosages, and primary source citations, enrich_drugs.py executes targeted domain queries via DuckDuckGo Search (DDGS). Searches were restricted to trusted medical repositories:
site:nih.gov(National Institutes of Health)site:asahq.org(American Society of Anesthesiologists)site:asra.com(American Society of Regional Anesthesia and Pain Medicine)site:heart.org(American Heart Association ACLS/PALS)site:dailymed.nlm.nih.gov(FDA Official Drug Labels)
Scraped HTML pages were cleaned using BeautifulSoup4 to remove non-clinical markup (navbars, scripts, footers), yielding clean text context blocks.
Stage 3: LLM Anti-Hallucination Prompting & Pydantic Schema Enforcement
The cleaned text context blocks were passed to the DeepSeek LLM (deepseek-chat) via OpenAI-compatible client interfaces. To prevent model hallucinations, strict system prompts were enforced:
- Zero-Tolerance Instruction: If a maximum absolute dose is not explicitly documented in the provided context or core guidelines, the model must return
0formaxDoserather than estimating. - Citation Tracking: The model was required to extract exactly two authoritative source titles with valid URLs.
Before accepting any LLM output into the production dataset, the response payload was validated against strict Pydantic schemas (Source and DrugEnrichment):
from pydantic import BaseModel, Field
class Source(BaseModel):
name: str = Field(description="Name of the authoritative peer-reviewed medical source")
url: str = Field(description="Direct, valid URL to the primary source document")
class DrugEnrichment(BaseModel):
drugClass: str = Field(description="Validated anatomical/therapeutic class of the drug.")
mechanism: str = Field(description="Validated mechanism of action.")
commonDoseAdult: str = Field(description="Validated common adult dosage string.")
pkPdParameters: str = Field(description="Validated PK/PD pharmacokinetic parameters.")
crucialClinicalInfo: str = Field(description="Validated crucial clinical warnings and precautions.")
lowDose: float = Field(description="Validated lower bound of recommended dose.")
highDose: float = Field(description="Validated upper bound of recommended dose.")
isMax: bool = Field(description="Flag indicating if the high dose represents a hard maximum.")
maxDose: float = Field(description="Validated absolute maximum safe dose (0 if unstated).")
units: str = Field(description="Validated dosing units (e.g., mg/kg, mcg/kg/min).")
route: str = Field(description="Validated route of administration (IV, IM, PO, ETT).")
notPerKg: bool = Field(description="Boolean set to True if dose is fixed, not weight-based.")
sources: list[Source] = Field(min_length=2, max_length=2, description="Exactly two verified citations.")
If a payload failed Pydantic validation (for example, if a dose bound was negative or a URL string was malformed), the item was rejected and an automated retry was triggered with tightened constraints. The validated output was serialized to drugs_enriched_v2.json and exported to drugs_enriched_v2.csv for peer review by clinical anesthesiologists.
4. Flutter State Engine: Reactive Math & Physiological Calculations
In an operating room environment, updating a patient's core parameters (such as changing body weight from 70 kg to 12 kg or age from 45 years to 3 years) must instantly update every dependent calculation across all active clinical screens without UI stutter.
Flutter State Management Evaluation
┌────────────────────────────────────────────────────────┐
│ PatientState Model │
│ Inputs: weightKg, ageYears, heightCm, sex │
└───────────────────────────┬────────────────────────────┘
│ (Calls notifyListeners())
▼
┌────────────────────────────────────────────────────────┐
│ Synchronous Math Getters │
│ • Ideal Body Weight (Devine) : < 0.01 ms │
│ • Body Surface Area (Mosteller) : < 0.01 ms │
│ • Age MAC (Mapleson) : < 0.01 ms │
│ • Maintenance Fluids (4-2-1) : < 0.01 ms │
│ • Pediatric ETT Size (Cole) : < 0.01 ms │
└───────────────────────────┬────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ Instantaneous UI Re-Render │
│ Zero Async Futures | Zero UI Jank | 60 FPS Smooth │
└────────────────────────────────────────────────────────┘
- Redux / BLoC: Evaluated for strict event-driven separation. However, BLoC introduces stream overhead and substantial boilerplate for simple, synchronous mathematical formulas.
- Riverpod: Offers robust dependency injection, but adds provider scope wrapping for simple patient input state.
- Provider with
ChangeNotifier(Selected): We implemented a centralizedPatientStatemodel extendingChangeNotifier. This class holds primary patient variables (weightKg,ageYears,heightCm,sex) and exposes synchronous getter methods for derived physiological metrics.
Physiological Math Engine Formulations
1. Ideal Body Weight (Devine Formula)
For patient height greater than 152.4 cm (5 feet), Ideal Body Weight (IBW) is computed as: $$\text{IBW}{\text{male}} = 50.0 + 2.3 \times \left(\frac{\text{height}{\text{cm}} - 152.4}{2.54}\right)$$ $$\text{IBW}{\text{female}} = 45.5 + 2.3 \times \left(\frac{\text{height}{\text{cm}} - 152.4}{2.54}\right)$$
2. Body Surface Area (Mosteller Formula)
Body Surface Area (BSA) in square meters ($m^2$) is calculated synchronously: $$\text{BSA} = \sqrt{\frac{\text{height}{\text{cm}} \times \text{weight}{\text{kg}}}{3600}}$$
3. Age-Adjusted Minimum Alveolar Concentration (Mapleson Equation)
Age reduces volatile anesthetic requirements. The age-adjusted MAC is derived via the Mapleson formula: $$\text{MAC}{\text{age}} = \text{MAC}{\text{baseline}} \times 10^{-0.00269 \times (\text{age}_{\text{years}} - 40)}$$
4. Maintenance Fluid Rate (Holliday-Segar 4-2-1 Rule)
Fluid maintenance requirements are calculated dynamically based on weight thresholds:
- First 10 kg: $\text{weight}_{\text{kg}} \times 4\text{ mL/hr}$
- 11 to 20 kg: $40 + (\text{weight}_{\text{kg}} - 10) \times 2\text{ mL/hr}$
- Above 20 kg: $60 + (\text{weight}_{\text{kg}} - 20) \times 1\text{ mL/hr}$
5. Pediatric Endotracheal Tube (ETT) Size & Depth (Modified Cole Formula)
For pediatric airway management: $$\text{ETT Size (Uncuffed)} = 3.5 + \left(\frac{\text{age}_{\text{years}}}{4}\right) \quad \text{[rounded to nearest 0.5 mm]}$$ $$\text{ETT Depth (cm)} = \text{ETT Size} \times 3.0$$
Because all derived calculation getters execute synchronously in memory in under 0.1 milliseconds, invoking notifyListeners() on input change triggers immediate UI updates across all views without requiring FutureBuilder or asynchronous stream overhead.
5. Opioid Equianalgesic Converter: Math Engine & Embedded Verification
Converting between parenteral and oral opioid formulations requires precise handling of drug potencies, routes, and incomplete cross-tolerance reduction factors.
The Mathematical Conversion Algorithm
To prevent dosing errors when converting between drugs with different units (such as Fentanyl in micrograms and Morphine in milligrams), the conversion engine normalizes all inputs through a central IV Morphine equivalent baseline table (opioid_factors.json).
┌────────────────────────────────────────────────────────┐
│ Step 1: Normalize Input Dose to Baseline IV Morphine │
│ DoseInMg = (SelectedFrom == Fentanyl) │
│ ? DoseFrom / 1000.0 │
│ : DoseFrom │
└───────────────────────────┬────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ Step 2: Apply Cross-Tolerance & Equianalgesic Scaling │
│ ConvertedDoseMg = ((100 - CrossTolerancePercent)/100) │
│ * (DoseInMg / FactorFrom) │
│ * FactorTo │
└───────────────────────────┬────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ Step 3: Convert Output to Target Display Units │
│ FinalDisplayDose = (SelectedTo == Fentanyl) │
│ ? ConvertedDoseMg * 1000.0 │
│ : ConvertedDoseMg │
└────────────────────────────────────────────────────────┘
Step 1: Unit Normalization to Baseline IV Morphine
If the source medication is dosed in micrograms (e.g., Fentanyl IV), the input dose is normalized to milligrams: $$\text{Dose}{\text{mg}} = \begin{cases} \frac{\text{Dose}{\text{from}}}{1000.0} & \text{if unit is }\mu\text{g} \ \text{Dose}_{\text{from}} & \text{if unit is mg} \end{cases}$$
Step 2: Cross-Tolerance Reduction and Equianalgesic Ratio Scaling
Applying incomplete cross-tolerance percentage reduction ($R_{\text{cross}}$): $$\text{Dose}{\text{converted, mg}} = \left(\frac{100 - R{\text{cross}}}{100}\right) \times \left(\frac{\text{Dose}{\text{mg}}}{\text{Factor}{\text{from}}}\right) \times \text{Factor}_{\text{to}}$$
Step 3: Target Unit Conversion
If the target drug requires microgram display (e.g., Fentanyl or Sufentanil): $$\text{FinalDisplayDose} = \begin{cases} \text{Dose}{\text{converted, mg}} \times 1000.0 & \text{if target unit is }\mu\text{g} \ \text{Dose}{\text{converted, mg}} & \text{if target unit is mg} \end{cases}$$
In-App Reference Verification Mechanisms
To allow clinicians to verify equianalgesic conversions without leaving the app context, we evaluated static external browser links versus embedded dynamic webview overlays.
- Static External Browser Links: Opening an external browser context disrupts clinical focus and clears active app state in memory.
- Embedded Dynamic WebViews (Selected): We integrated
webview_flutteralongsidefont_awesome_flutteraction buttons. Tapping the verification icon programmatically constructs an exact query string (e.g., "convert 10.0 mg Morphine IV to Oxycodone PO for 40 yr old male 70 kg") and presents a live, peer-reviewed medical search overlay (WebViewScreen) directly within the app stack.
6. Platform Optimizations & Android API 36 Compliance
To ensure long-term stability, security, and performance on modern mobile operating systems, we implemented several key platform-level engineering optimizations:
- Android 16 (API Level 36) Targeting: Updated build configurations (
build.gradle) to compile against API Level 36, ensuring full compliance with Google Play's latest security, edge-to-edge layout, and background service execution rules. - R8 Code Shrinking & Obfuscation: Enabled full R8 shrinking in
android/gradle.properties. Unused code paths and unused resources were stripped, significantly reducing the final APK/AAB package size and accelerating execution speed. - High-Contrast Dark Mode Styling: Built UI themes around Google Fonts (
OutfitandInter) with high-contrast surface palettes optimized specifically for low-light operating room environments. - Native Splash Screen & Icon Asset Pipeline: Integrated
flutter_native_splashandflutter_launcher_iconsto eliminate initial display flash during cold boot on both Android and iOS devices.
7. Summary Matrix of Architectural Trade-Offs
The table below summarizes the core engineering trade-offs made during the design and development of Aether Anesthesia Calculator:
| Subsystem | Selected Architecture | Rejected Alternative | Engineering Rationale |
|---|---|---|---|
| Data Storage | Hybrid Offline Asset Bundle | Cloud REST/GraphQL API | Guarantees 100% offline reliability in lead-lined ORs with sub-millisecond read speeds. |
| Data Extraction | Multi-Stage Python Pipeline | Manual Data Entry | Eliminates human transposition errors while automating domain scraping and verification. |
| Data Integrity | DeepSeek + Pydantic Schema | Unconstrained LLM Generation | Enforces strict type checking, zero hallucination fallback (maxDose=0), and verified citations. |
| State Management | Provider + ChangeNotifier |
BLoC / Redux | Provides synchronous sub-millisecond reactive calculations without stream boilerplate. |
| Clinical Verification | Embedded Dynamic WebViews | External Browser Navigation | Preserves application state and clinical context during bedside verification checks. |
| Build Optimization | R8 Code Shrinking (API 36) | Default Unoptimized Build | Minimizes application binary footprint and enhances cold-boot startup speed. |
8. Building Compliance-Critical Software with Blackspring
The development of Aether Anesthesia Calculator highlights Blackspring's core engineering philosophy: Bespoke. Secure. Compliant.
When engineering software for regulated industries—whether healthcare, medical devices, logistics, or enterprise ERP systems—off-the-shelf templates and hasty prototypes are inadequate. High-stakes applications require:
- Rigorous Data Pipelines: Automated data ingestion, strict schema validation, and auditability.
- Resilient Offline Architecture: High performance under hostile network conditions.
- Precision Engineering: Clean code architectures designed for safety and reliability.
At Blackspring, we partner with enterprises to design, build, and deploy mission-critical software solutions engineered to exact regulatory and performance standards.
Building a compliance-sensitive or mission-critical application? Contact the Blackspring Engineering Team to discuss your architectural requirements.
Author Bio
Blackspring Engineering Practice Blackspring is a Nepal-based software engineering firm specializing in bespoke, secure, and compliant software for healthcare, logistics, and enterprise systems. Website: blackspring.com.np | GitHub: blackspringnepal