docs/domains/airmid/ (API notes, ADRs, deep topic guides) — reconciled here by linking, kept beside the code as supporting material rather than a second canonical source (§2, §13).Airmid — Evidence-Based Phytotherapy and Botanical Intelligence Platform
Airmid (the Celtic goddess of herbalism and healing, who catalogued all the healing properties of plants on her cloak) is a comprehensive scientific platform for evidence-based phytotherapy and natural product drug discovery. The domain spans the full spectrum from ethnobotanical knowledge of traditional medicine systems through computational chemistry, clinical decision support, pharmacogenomics, microbiome pharmacology, AI-driven discovery, and regulatory compliance.
Airmid is implemented as a pure library domain: 19 packages under
libs/airmid/, with no apps/airmid/ or services/airmid/ directories. Each
package targets a distinct scientific discipline, and the libraries are consumed
by other applications in the Oshun ecosystem. The Airmid libraries currently
import no other Oshun domain packages; any cross-domain integration with Sophia
(research corpus/knowledge graph) or other domains is planned, not yet
implemented in code. Phase 35 of TODOS.md remains the canonical planning
source for the domain scope.
1. Core Phytotherapy Knowledge Base#
Foundational types, compound database, and botanical data structures shared
across all Airmid libraries (@airmid/core).
Phytotherapy is the scientific study and practice of using plant-derived substances as medicines. It differs from herbalism in its emphasis on chemical characterization, clinical evidence, and mechanistic understanding. Every other Airmid library builds on the types and validation logic defined here.
- Domain entity classes: 15 entity classes —
BotanicalSpecies,PhytochemicalCompound,ClinicalTrial,EvidenceRecord,DrugHerbInteraction,AdverseEvent,TraditionalUse,PharmacognosyMonograph,ProteinTarget,BiologicalPathway,QualityMarker,DNABarcode,SpectroscopicFingerprint,FormulationRecipe,ConservationStatus— each wrapping a validated raw-data interface with computed properties and atoJSON()serializer. - Taxonomic classification: Full Linnaean taxonomy (Kingdom → Phylum → Class
→ Order → Family → Genus → Species, plus infraspecific subspecies, variety,
cultivar ranks) with the
TaxonomicRankenum and synonym handling. - Botanical name handling: Binomial nomenclature management with accepted name, taxonomic authority, synonym cross-referencing, and common-name lists, all enforced by Zod schemas.
- Dosage guidelines: Structured dosage data including dose range (min/max),
frequency, preparation method (
DosageForm,PreparationType), unit, and duration — with validation. - Reference-data constants: 12 CYP450 enzymes, curated common herb-drug interactions, 25 WHO essential-medicine herbs, GRADE quality factors, 20 therapeutic categories, 118 element symbols, 10 medicinal plant families, and CYP450 compound-class profiles.
- Domain errors and events: 8 typed error classes (
AirmidErrorand subclasses) and 13 domain event types (AirmidEventType/createAirmidEvent). - Database schema (
@airmid/database): PostgreSQL schema via Knex.js — 17 base tables (botanical species, phytochemical compounds, plant-compound associations, clinical trials, evidence records, drug-herb interactions, adverse-event reports, traditional-use records, pharmacopoeia monographs, regulatory statuses, DNA barcodes, spectroscopic fingerprints, protein targets, compound-target associations, biological pathways, conservation records, audit logs), 5 materialized views, 35 enum types, full-text indexes, update triggers, and soft-delete support — with matching Zod schema modules.
2. Ethnobotanical Knowledge Systems#
Comprehensive database of traditional medicine systems worldwide and their use
of medicinal plants (@airmid/ethno).
Ethnobotany studies the relationship between humans and plants across cultures — particularly traditional medicinal use passed down through generations. This knowledge base often reveals biologically active compounds later validated by modern science. Converging use of the same plant across independent cultural traditions is one of the strongest signals that genuine biological activity exists, even before any clinical trial has been run.
- Traditional medicine system taxonomy: Structured representation of major
traditional medicine systems with their own pharmacological frameworks:
- TCM (Traditional Chinese Medicine): Herb nature (cold/hot/warm/cool/neutral — referring to the thermal effect on the body, not temperature), flavor (bitter/sweet/sour/pungent/salty — each associated with specific organ affinities), channel tropism (which meridians the herb affects), and therapeutic category.
- Ayurveda: Rasa (the primary taste perceived in the mouth), vipaka (the post-digestive effect after metabolism), virya (potency — whether heating or cooling the body), prabhava (special or unexplained actions beyond the other parameters), and dosha modulation (whether the herb balances or aggravates Vata/Pitta/Kapha).
- Unani medicine: The Islamic-Galenic system deriving from Avicenna — Mizaj (temperament, from hot/cold combined with wet/dry) and organ affinities within the Unani humoral framework.
- African traditional medicine: Herb roles in West African (Yoruba, Akan), East African, Southern African (Zulu, Xhosa), and Central African traditional healing systems — including cultural context, preparation methods, and ritual uses.
- Indigenous Americas: Traditional plant uses from Mesoamerican (Aztec, Maya), Andean (Inca, Quechua), and North American indigenous traditions.
- Cross-system correlation: Map the same plant across multiple traditional systems to identify convergent traditional uses — convergence across independent cultures suggests genuine biological activity worth investigating.
- Modern phytotherapy integration: Bridge traditional use evidence (which can reach thousands of years) with modern pharmacological data, creating evidence profiles that combine both.
- Traditional use claim extraction: NLP-powered extraction of traditional use claims from ancient texts in Chinese, Sanskrit, Arabic, and other classical medical languages.
3. Computational Phytochemistry#
In-silico tools for analyzing and predicting the physicochemical and biological
properties of natural product compounds (@airmid/phytochem).
Phytochemistry is the chemistry of plant-derived compounds. Computational phytochemistry applies in-silico (computer-based) methods to predict the behavior and properties of these compounds without requiring laboratory experiments. This allows rapid triage of thousands of natural products to identify the most promising candidates for further investigation.
Natural Products Compound Database#
The foundation of this module is a curated compound database that goes beyond simple structure storage — each entry carries a full chemical and biological profile.
- 55 curated compound entries (
NATURAL_PRODUCTS_DATABASE): each with full chemical and biological profile — molecular structure, formula, external identifiers (PubChem CID, ChEMBL ID, KEGG ID, HMDB ID, DrugBank ID where available), natural source, and pharmacological classification — with lookup helpers (searchCompounds,getCompoundById,getCompoundsBySpecies,getCompoundsByClass).
Molecular Property Calculation#
The following physicochemical descriptors are calculated from molecular structure and feed into all downstream drug-likeness and ADMET prediction steps:
- Lipophilicity (logP): The partition coefficient between octanol and water — a key indicator of membrane permeability, absorption, and distribution. Most oral drugs have logP between 0 and 5.
- Topological Polar Surface Area (TPSA): Calculated from polar atoms in the molecule. TPSA > 140 Ų strongly predicts poor oral absorption; > 60 Ų predicts poor CNS penetration.
- Molecular weight: Lipinski's classic cutoff is < 500 Da for oral drug-like molecules.
- Rotatable bonds: Measures molecular flexibility — highly flexible molecules (> 10 rotatable bonds) often have poor oral bioavailability.
- H-bond donors and acceptors: Hydrogen bond donors (≤ 5) and acceptors (≤ 10) are Lipinski Ro5 criteria for oral bioavailability.
- QED (Quantitative Estimate of Drug-likeness): A composite score from 0–1 derived from eight molecular properties that reflects drug-likeness, where 1 is maximally drug-like.
- Fsp3 (fraction of sp3 carbons): Measures three-dimensionality of the molecule — higher Fsp3 is associated with better drug candidate success rates in development.
Drug-Likeness Assessment#
Several established rule-sets filter out compounds unlikely to be orally bioavailable or safe. Airmid implements all five major filters:
- Lipinski Ro5: The foundational oral bioavailability filter (≤ 500 Da, ≤ 5 H-bond donors, ≤ 10 H-bond acceptors, logP ≤ 5).
- Veber rules: ≤ 10 rotatable bonds and TPSA ≤ 140 Ų for oral bioavailability.
- Ghose filter: More restrictive drug-likeness criteria (160–480 Da, logP −0.4 to 5.6, 40–130 atoms, 20–70 molar refractivity).
- Egan filter: For blood-brain barrier permeability assessment (TPSA ≤ 131.6 Ų, AlogP98 ≤ 5.88).
- Muegge lead-likeness: Lead optimization criteria for molecules that will be further optimized in medicinal chemistry.
ADMET Prediction#
ADMET (Absorption, Distribution, Metabolism, Excretion, Toxicity) prediction estimates how a compound will behave in the body before any wet-lab experiments are run. This allows natural product researchers to identify potential liabilities early and prioritize compounds that are more likely to succeed.
- Absorption prediction: Oral bioavailability, Caco-2 permeability (model of intestinal absorption), and P-glycoprotein efflux prediction.
- Distribution prediction: Blood-brain barrier permeability, plasma protein binding fraction, volume of distribution.
- Metabolism prediction: Phase I biotransformations (CYP-mediated hydroxylation, demethylation, N-dealkylation), Phase II conjugations (glucuronidation, sulfation, glutathione conjugation), and gut microbiota biotransformation.
- Excretion prediction: Renal clearance, biliary excretion, and half-life estimation.
- Toxicity prediction: Ames mutagenicity (bacterial mutation assay prediction), hERG cardiotoxicity (cardiac ion channel blockade that can cause potentially fatal arrhythmia), hepatotoxicity (liver injury potential), LD50 estimation, and GHS (Globally Harmonized System) toxicity classification.
Chemical Structure Utilities#
Reliable compound identity management is a prerequisite for cross-database data integration. These utilities ensure compounds can be unambiguously identified and compared across PubChem, ChEMBL, and internal databases:
- 3D structure management: ETKDG conformer generation (the gold standard in cheminformatics for 3D conformer generation), pharmacophore feature identification, and molecular volume calculation.
- SMILES canonicalization: Standardize SMILES (Simplified Molecular Input Line Entry System) representations to a canonical form — critical for compound identity matching across databases.
- InChIKey generation and validation: Generate and validate IUPAC International Chemical Identifiers — the standard for unambiguous chemical identity.
- CAS number validation: CAS Registry Number check digit validation using the official CAS algorithm.
4. Evidence and Clinical Research#
Comprehensive access to and analysis of the clinical evidence base for herbal
medicines (@airmid/evidence).
The quality of evidence for herbal medicines varies enormously — from high-quality randomized controlled trials to centuries-old traditional use with no modern data. A platform that treats all these sources equally would be clinically misleading. GRADE (Grading of Recommendations Assessment, Development and Evaluation) is the international standard for rating evidence quality, and it is applied throughout Airmid to every herb-indication pair.
- Clinical trial integration: Search and retrieve ClinicalTrials.gov data (including WHO ICTRP and EU CTR) with eligibility criteria extraction, intervention parsing for herbal products, outcome measure standardization, and trial status tracking.
- Systematic review database: Cochrane and other systematic review data with PRISMA (Preferred Reporting Items for Systematic Reviews and Meta-Analyses) extraction — PRISMA is the reporting standard that ensures completeness and transparency.
- Meta-analysis results: Forest plot data (the visual display of pooled trial results), pooled effect sizes with confidence intervals, and heterogeneity statistics (I², Tau²) that indicate how consistent results are across trials.
- GRADE evidence grading: Systematic GRADE certainty assessment (High/Moderate/Low/Very Low) for each herb-indication pair — GRADE accounts for risk of bias, inconsistency, indirectness, imprecision, and publication bias.
- Risk of bias assessment: Cochrane Risk of Bias 2.0 tool domains: randomization sequence generation, allocation concealment, blinding of participants/personnel, blinding of outcome assessment, attrition bias, selective reporting.
- Effect size reporting: Cohen's d (standardized mean difference), Number Needed to Treat (NNT — how many patients need treatment for one to benefit), Number Needed to Harm (NNH), and Likelihood of Harm to Benefit ratio (LHH).
- Evidence search: Semantic search across PubMed, trial registries, and review databases with relevance ranking for specific herb-indication queries.
- Research corpus manager: Curate collections of research for specific herbs or indications, with deduplication and quality filtering.
- Evidence freshness monitoring: Track whether the evidence base for specific herbs is outdated (no new trials in > 5 years) and flag for systematic update.
5. Drug-Herb Interaction Decision Support#
Clinical decision support for identifying and managing herb-drug interactions in
patient care (@airmid/interactions).
Herb-drug interactions are clinically significant in up to 20% of patients using herbal medicines concurrently with pharmaceutical drugs. The most significant interactions occur at the level of CYP450 enzymes — the liver enzymes responsible for metabolizing most pharmaceutical drugs. When a herb inhibits or induces these enzymes, it can dramatically increase or decrease the plasma levels of co-administered drugs, sometimes to dangerous levels.
Interaction Database#
The interaction database is the primary reference for clinical decision support, capturing not just severity but the mechanistic detail a clinician needs to manage the interaction:
- 80+ documented interactions:
HERB_DRUG_INTERACTION_DATABASE— clinically validated herb-drug interaction entries with herb name and binomial, drug name and class, severity, mechanism, clinical evidence level, onset time, management guidance, monitoring parameters, safer alternatives, and literature references. - Pharmacokinetic interactions — CYP450: The cytochrome P450 enzyme system
is responsible for metabolizing approximately 60% of all pharmaceutical drugs.
Herbal inhibitors or inducers of these enzymes can dramatically alter drug
levels:
- CYP3A4: Metabolizes ~50% of drugs. St. John's Wort is a potent inducer, reducing levels of cyclosporine, HIV antiretrovirals, and oral contraceptives.
- CYP2D6: Metabolizes antidepressants, opioids, and beta-blockers.
- CYP2C9: Metabolizes warfarin, NSAIDs, and some diabetes drugs.
- CYP2C19: Metabolizes proton pump inhibitors, clopidogrel, and some antidepressants.
- CYP1A2, CYP2B6, CYP2C8, CYP2E1: Additional clinically important enzymes.
- Pharmacokinetic interactions — Transporters: P-glycoprotein (P-gp) and OATP transporter modulation — herbs can alter how drugs are transported across cell membranes, affecting their absorption, tissue distribution, and elimination.
- Pharmacodynamic interactions: Synergistic, additive, and antagonistic interactions at the mechanism level — e.g., Ginkgo biloba adding to anticoagulant effects of warfarin (synergistic, increasing bleeding risk).
Alert System#
The alert system turns the interaction database into actionable clinical decision support, ranging from quantitative inhibition prediction to patient-facing counseling language:
- Severity classification: A 5-level severity scale — Contraindicated (absolute avoid) / Major (potentially life-threatening) / Moderate (clinically significant but manageable) / Minor (limited clinical significance) / Theoretical (pharmacological reasoning only, no clinical data).
- Overall risk assessment:
checkInteractionsaggregates a patient's herb and drug lists into an overall risk level, surfacing contraindications and per-interaction detail. - Inhibition magnitude prediction:
predictInhibitionMagnitude/checkCYPInteractionprovide quantitative CYP inhibition prediction rather than just categorical flags, drawing on the CYP450 profile and substrate-drug databases. - Transporter interactions:
checkTransporterInteraction/predictTransporterEffectcover P-glycoprotein and other transporter modulation. - Patient counseling text generation:
generatePatientCounselingproduces patient-appropriate interaction counseling language for pharmacist and clinician communication.
Override tracking with mandatory justification documentation is implemented in
@airmid/clinical (audit and compliance — see §17), not in
@airmid/interactions.
6. Molecular Docking and Computer-Aided Drug Design#
Computer-aided drug design (CADD) tools for natural product lead identification
and optimization (@airmid/docking).
Molecular docking is a computational method that predicts how a small molecule (ligand) binds to a protein target (receptor) — identifying which natural product compounds might have therapeutic activity before laboratory testing. This dramatically reduces the cost of early-stage drug discovery by computationally screening hundreds of compounds to identify a handful worth testing in the lab.
Docking Core#
The docking core implements the full workflow from protein preparation to scored binding results:
- AutoDock Vina scoring: Molecular docking using the AutoDock Vina scoring function — the most widely used free docking engine in academic drug discovery, providing predicted binding affinity in kcal/mol.
- Protein preparation: Preparing protein crystal structures for docking: adding missing atoms and residues, adding hydrogen atoms (not visible in X-ray structures), assigning Gasteiger partial charges.
- Binding site detection: fpocket-inspired cavity detection algorithm that identifies druggable pockets on the protein surface — where small molecules can bind.
- Grid box optimization: Automated grid box definition around detected binding sites, defining the search space for the docking algorithm.
- Virtual screening: Screen large compound libraries against a target protein to identify hits — ranking hundreds of compounds by predicted binding affinity to prioritize which to test experimentally.
- PAINS filtering: Pan-Assay Interference Compounds (PAINS) filtering using 60 SMARTS alerts from Baell & Holloway 2010 — removing compounds that give false positives in many bioassays due to non-specific reactivity, not genuine target engagement.
- Consensus scoring: Combine multiple scoring functions (Vina, Glide, ChemScore) for more reliable hit ranking than any single scoring function alone.
Compound Selection and Similarity#
Before screening, compound libraries must be filtered and diversified. These tools handle that triage step:
- Tanimoto chemical similarity: Cluster and filter compound libraries by structural similarity using Morgan/ECFP fingerprints and Tanimoto coefficient — grouping structurally related compounds and selecting diverse representatives.
- MaxMin diversity selection: Select maximally chemically diverse compound subsets from large libraries for screening — ensuring broad coverage of chemical space.
Advanced CADD#
Beyond standard single-target docking, Airmid provides tools for multi-target and structure-activity analyses:
- Inverse docking: Screen a compound against a panel of 32 diverse protein targets to predict which targets it is most likely to bind — identifying mechanism of action for unknown natural products.
- Boltzmann target probability: Normalize docking scores across multiple targets to probability distributions for interpretable target prediction confidence.
- Polypharmacology profiling: Predict multi-target activity profiles for natural product compounds — most natural products act on multiple targets simultaneously, which can be therapeutically advantageous.
- QSAR modeling: Quantitative Structure-Activity Relationship models using Morgan/ECFP fingerprints with OECD-compliant validation (external test set, applicability domain, mechanistic interpretation).
Molecular Dynamics#
Molecular dynamics simulation provides a more accurate picture of binding than static docking, accounting for protein flexibility and solvent effects:
- Molecular dynamics (MD) specification: Define and configure MD simulations using AMBER, CHARMM, or OPLS-AA force fields — the parameters that describe atomic interactions in the simulation.
- Trajectory analysis: Analyze MD simulation trajectories with RMSD (Root Mean Square Deviation — how much the protein structure deviates from its starting conformation), RMSF (per-residue flexibility), radius of gyration (protein compactness), SASA (Solvent Accessible Surface Area), and H-bond occupancy.
- MM-PBSA binding free energy: End-point free energy calculations (Molecular Mechanics Poisson-Boltzmann Surface Area) for binding affinity refinement — more accurate than pure docking scores for ranking closely related compounds.
7. Network Pharmacology#
Systems biology approach for understanding how natural products interact with
biological networks (@airmid/network).
Network pharmacology treats pharmacology as a network problem: rather than asking "what is the single target of this drug?", it asks "how does this compound affect the entire network of proteins and pathways?" This is particularly suited to herbal medicines, which typically contain hundreds of compounds each potentially active on multiple targets. A single herb can simultaneously modulate inflammation, oxidative stress, and immune signaling pathways through different compounds acting on different proteins in the same disease network.
- Target identification: Identify protein targets for natural product compounds from bioactivity databases (ChEMBL, BindingDB) and literature mining.
- Protein-protein interaction (PPI) networks: Construct and analyze PPI networks using STRING database data — where proteins that physically interact or co-regulate each other are connected.
- Network topology metrics: Degree centrality (how many connections), betweenness centrality (how often a node lies on shortest paths — key for identifying important hub proteins), eigenvector centrality (connected to other important nodes), and clustering coefficient.
- Pathway enrichment analysis: KEGG (Kyoto Encyclopedia of Genes and Genomes) pathway enrichment with Fisher's exact test and FDR (False Discovery Rate) correction — identifying which biological pathways are over-represented among the predicted targets.
- Gene Ontology (GO) analysis: GO Biological Process (what the proteins do), Molecular Function (how they do it), and Cellular Component (where they are) enrichment analysis.
- Multi-layer network integration: Integrate compound-target, target-pathway, pathway-disease, and protein-protein interaction networks into a unified multi-layer network for holistic understanding.
- Synergy prediction: Predict synergistic effects between compounds in herbal formulas using network topology — compounds that act on different nodes of the same network module often show synergy.
- Disease module mapping: Map compound targets onto disease-associated protein modules in the human interactome — connecting natural product pharmacology to specific disease mechanisms.
8. Formulation Science#
Pharmaceutical formulation science tools for developing herbal medicines
(@airmid/formulation).
Formulation science determines how an active compound is delivered to the body. Extraction method, dosage form, delivery system, and stability all profoundly affect whether a herbal product is clinically effective. A compound with excellent in-vitro activity but poor bioavailability will fail in clinical use unless the formulation problem is solved.
- Drug combination synergy analysis: Four mathematical models for assessing synergy/antagonism between compounds: Chou-Talalay Combination Index (CI < 1 = synergy, = 1 = additivity, > 1 = antagonism), Bliss independence model (probabilistic independence), Loewe additivity (dose additivity), and Highest Single Agent (HSA) model.
- Antagonism detection: Pharmacokinetic antagonism (one compound accelerates elimination of another), pharmacodynamic antagonism (opposing mechanisms), chemical antagonism (compounds react and neutralize each other), and physical antagonism (complexation, precipitation).
- Extraction chemistry: 9 extraction methods optimized for 30+ compound classes — decoction (aqueous boiling, traditional for polysaccharides), maceration (cold water or alcohol soaking), percolation, supercritical CO₂ extraction (preserves volatile compounds, no residual solvent), ultrasonic-assisted extraction, microwave-assisted extraction, pressurized liquid extraction, steam distillation (for essential oils), and fermentation processing.
- Stability and shelf-life prediction: Arrhenius accelerated stability testing (using elevated temperature to predict long-term stability), ICH climate zone-adjusted shelf-life prediction (ICH Q1A guidelines), and degradation kinetics modeling.
- Bioavailability enhancement: 15+ evidence-based technologies for improving absorption of poorly bioavailable natural products: polymeric nanoparticles, liposomes, phospholipid complexes (phytosomes), cyclodextrin inclusion complexes, piperine co-administration (BioPerine — blocks P-gp efflux), and others.
- Amorphous solid dispersions: Converting crystalline natural products to amorphous form dispersed in a polymer carrier dramatically increases dissolution rate for poorly soluble compounds.
- Standardization strategy: Selecting chemical markers to standardize against, setting specification ranges, and selecting analytical methods (HPLC, UV, titration) appropriate for each marker compound.
9. Microbiome Pharmacology#
The science of how gut microbiota transforms and mediates herbal medicine
effects (@airmid/microbiome).
The gut microbiome plays a central role in the pharmacology of many herbal medicines — either transforming inactive compounds into active metabolites (e.g., gut bacteria convert ellagitannins to urolithins, which are the actual anti-inflammatory agents) or being directly modulated by plant polysaccharides and polyphenols. Ignoring the microbiome leads to incomplete and sometimes incorrect predictions about a herb's clinical effect, particularly because only 30–50% of people can convert certain precursor compounds into their bioactive forms.
- Prebiotic effect database: 45+ herb-microbiome prebiotic interactions — polysaccharides (inulin, beta-glucan, arabinogalactan), polyphenols, oligosaccharides, and dietary fibers that selectively promote beneficial bacteria (Lactobacillus, Bifidobacterium) or suppress pathogens.
- Microbial metabolite production: 30+ microbial metabolites including SCFAs (short-chain fatty acids: butyrate, propionate, acetate — primary energy sources for colonocytes and regulators of inflammation), secondary bile acids (deoxycholic acid, lithocholic acid), TMAO (trimethylamine N-oxide, a cardiovascular risk marker), equol (a soy isoflavone metabolite with estrogenic activity), urolithins (ellagitannin metabolites), indoles, and p-cresol.
- Dysbiosis correction: 18 clinical dysbiosis patterns with herbal correction protocols — IBD-associated dysbiosis, IBS-associated patterns, SIBO (small intestinal bacterial overgrowth), C. difficile post-antibiotic dysbiosis, and obesity-associated microbiome composition.
- Enterotype characterization: The three major human gut microbiome enterotypes (Bacteroidetes-dominated, Prevotella-dominated, Ruminococcus-dominated) and how they affect the metabolism of specific herbal compounds.
- Herb-microbiome bidirectional modulation: Model how herbs modify the microbiome composition, and how microbiome composition in turn modifies the metabolism and therefore the clinical effect of the same herbs.
10. Precision Herbal Medicine#
Personalized herbal medicine recommendations based on individual genetic and
phenotypic variation (@airmid/precision).
Precision medicine recognizes that genetic variation between individuals — particularly in drug-metabolizing enzymes — means the same dose of a herbal medicine can have profoundly different effects in different people. A poor metabolizer of CYP2D6 may accumulate herb-derived compounds to toxic levels on a standard dose that a normal metabolizer handles safely. This module integrates that genetic information into dosing decisions.
Pharmacogenomics#
The pharmacogenomics sub-module covers the major CYP450 enzymes and other metabolic genes whose variation is clinically actionable for herbal medicine:
- CPIC CYP450 databases: Clinical Pharmacogenomics Implementation Consortium (CPIC) — the gold standard for translating pharmacogenomic test results into clinical recommendations — for CYP2D6, CYP2C19, CYP2C9, CYP3A4, CYP3A5, CYP1A2, CYP2B6, CYP2C8, CYP2E1 allele databases.
- Activity Score calculation: CPIC Activity Score method assigns a numerical score to each CYP allele (0 = no function, 0.5 = decreased function, 1 = normal function), then sums scores across the two diploid alleles to predict phenotype.
- Metabolizer classification: Poor metabolizer (PM), Intermediate metabolizer (IM), Normal metabolizer (NM), and Ultra-rapid metabolizer (UM) phenotype classification — a PM for CYP2D6 may have dramatically different responses to herbs metabolized by this enzyme.
- NAT2 acetylator status: N-acetyltransferase 2 (NAT2) slow/intermediate/rapid acetylator classification — affects metabolism of herbs containing aromatic amines and hydrazines.
- UGT1A1 and Gilbert's syndrome: Bilirubin metabolism variation and effects on drug glucuronidation — relevant for herbs that undergo glucuronidation.
- COMT Val158Met: Catechol-O-methyltransferase polymorphism affects metabolism of catechol-containing phenolic compounds common in many herbs (green tea catechins, catechols in herbal pigments).
- MTHFR methylation: MTHFR (methylenetetrahydrofolate reductase) polymorphism affecting the methylation pathway and folate metabolism — relevant for herbs affecting one-carbon metabolism.
Genotype-Phenotype Database#
Beyond enzyme genotyping, this section captures microbiome-level genetic variation that determines whether certain phytochemical conversions can occur:
- 48 herb-gene-phenotype interactions: Documented interactions with CPIC evidence levels — e.g., St. John's Wort effectiveness varies with CYP2C19 genotype.
- Microbiome-phenotype interactions: Equol production status (only 30–50% of the population converts daidzein to equol, determining whether soy isoflavones have estrogenic effects), ginsenoside biotransformation by specific bacteria, and urolithin metabotypes (A, B, or 0 — only metabotype A converts ellagitannins to the bioactive urolithin A).
- Genotype-informed dose adjustment: Specific dose adjustment recommendations for commonly dosed herbal products when genotype data is available.
11. Quality Control and Authentication#
Analytical chemistry and pharmacognosy tools for ensuring herbal product quality
(@airmid/quality).
Herbal product quality is a documented, widespread problem. Adulteration (substituting cheaper or related species), substitution, and contamination have been found in commercial herbal products globally. Multiple analytical techniques provide orthogonal lines of evidence for authentication — a single technique can be fooled, but convergent evidence from DNA barcoding, spectroscopy, and chromatography is very difficult to fake.
- DNA barcoding authentication: Species authentication using Needleman-Wunsch pairwise sequence alignment against reference databases — comparing ITS2 (internal transcribed spacer 2), rbcL, and matK barcode regions to identify species from plant material even when morphological features are destroyed by processing.
- Spectroscopic fingerprinting: FTIR (Fourier Transform Infrared), NIR (Near Infrared), Raman, and UV-Vis spectral fingerprint matching — each provides a characteristic spectral "fingerprint" for plant species and preparations.
- Chromatographic profiling: HPLC (High Performance Liquid Chromatography), UPLC (Ultra Performance Liquid Chromatography), GC-MS (Gas Chromatography-Mass Spectrometry for volatile compounds), and TLC (Thin Layer Chromatography) reference profiles for comparison against pharmaceutical standards.
- Marker compound quantification: Quantitative assay specification checking against pharmacopoeial limits (e.g., echinacoside content in Echinacea must meet USP minimum).
- Adulteration detection: Multi-method detection combining spectroscopic, genomic, and chromatographic evidence — different adulterants are detectable by different methods.
- Quality grading: Composite quality grade (A/B/C/D/F) from multiple analytical dimensions — providing an overall quality score interpretable by non-specialists.
- Pharmacopoeial compliance: Compliance checking against USP (United States Pharmacopeia), PhEur (European Pharmacopoeia), BP (British Pharmacopoeia), JP (Japanese Pharmacopoeia), ChP (Chinese Pharmacopoeia), and IP (Indian Pharmacopoeia) specifications.
12. Safety and Toxicology#
Patient protection systems for identifying and managing herbal medicine risks
(@airmid/safety).
Safety signals for herbal medicines are harder to detect than for pharmaceutical drugs because herbal products are often self-prescribed, not reported to pharmacovigilance systems, and attributed to other causes when adverse events occur. Airmid applies international causality assessment algorithms to systematically evaluate every safety signal.
- WHO-UMC causality assessment: World Health Organization-Uppsala Monitoring Centre causality algorithm for assessing whether an adverse event was caused by a specific herbal medicine — classifying causality as Certain/Probable/Possible/Unlikely/Unclassifiable/Unassessable.
- Naranjo ADR scale: The Naranjo algorithm for adverse drug reaction causality assessment, providing a numeric score (> 9 = definite, 5–8 = probable, 1–4 = possible, ≤ 0 = doubtful).
- Disproportionality signal detection: PRR (Proportional Reporting Ratio) and ROR (Reporting Odds Ratio) for pharmacovigilance signal detection — statistical methods used by regulatory agencies to identify safety signals from spontaneous adverse event reports.
- Hepatotoxicity assessment: RUCAM (Roussel Uclaf Causality Assessment Method) scoring for herb-induced liver injury, Hy's Law application (ALT > 3× ULN + bilirubin > 2× ULN = high risk of fatal liver injury), DILI (Drug-Induced Liver Injury) pattern classification via R-ratio (hepatocellular vs. cholestatic vs. mixed), severity grading, and a database of 25+ hepatotoxic herbs.
- Nephrotoxicity assessment: Nephrotoxic herb database with renal function-adjusted risk assessment and early nephrotoxicity biomarkers (KIM-1, NGAL, cystatin C, β2-microglobulin).
- Pregnancy safety: Safety database for 40+ herbs with evidence-based risk classification by trimester — many herbs that are safe in general are contraindicated in pregnancy (e.g., uterine stimulants).
- Pediatric safety: Safety limits for 20+ herbs in pediatric populations with age-adjusted dosing thresholds — children metabolize drugs differently and require separate safety assessments.
- Geriatric safety: Altered pharmacokinetics in elderly populations (reduced renal/hepatic clearance, altered protein binding, polypharmacy risk) for 15+ herbs.
- Toxic compound detection: 30+ toxic compound limits from USP, EU, WHO, TGA (Australia), and HKSAR regulatory standards — e.g., pyrrolizidine alkaloid limits, aristolochic acid limits.
- Contamination assessment: Heavy metals (lead, mercury, arsenic, cadmium), pesticide residues (organophosphates, pyrethroids, herbicides), mycotoxins (aflatoxins, ochratoxin A), and contamination standards from international regulatory frameworks.
13. Regulatory Affairs#
Global regulatory science for herbal medicine market authorization
(@airmid/regulatory).
The regulatory status of herbal medicines varies dramatically by country — a product considered a food supplement in the US may require a drug license in Germany, and the same extract might be a traditional medicine in China and a cosmetic ingredient in Japan. Navigating this landscape requires jurisdiction-by- jurisdiction knowledge that this module maps for over 30 countries.
- Pharmacopoeia compliance: USP, PhEur, BP, JP, ChP, and IP pharmacopoeial specification management — each pharmacopoeia has different specification requirements for the same plant.
- EMA/HMPC monograph system: European Medicines Agency/Committee on Herbal Medicinal Products classification — "well-established use" (≥ 30 years published evidence, ≥ 15 years in EU) vs. "traditional use" (≥ 30 years traditional use, ≥ 15 years in EU) classification, each with different data requirements.
- FDA/DSHEA dietary supplement framework: US Dietary Supplement Health and Education Act requirements — structure-function claims rules, new dietary ingredient notification (NDI) requirements, cGMP compliance.
- Global jurisdiction mapping: Market-by-market regulatory classification
across 30+ countries and jurisdictions (
GLOBAL_REGULATORY_DATABASE) — OTC medicine, prescription medicine, dietary supplement, traditional medicine, food ingredient, or regulated cosmetic. - Labeling requirements: Permissible label claims, mandatory warning statements, and country-specific labeling standards for each jurisdiction.
- Claims classification: Structure-function claims (permissible in US for supplements), health claims (require FDA authorization), disease claims (restricted to licensed medicines) — each has different evidence requirements and regulatory implications.
- Regulatory strategy builder: Design a global market access strategy for a specific herbal product — identifying which regulatory pathways are most efficient across target markets.
14. Sustainability and Conservation#
Conservation biology and ethical sourcing intelligence for medicinal plants
(@airmid/sustainability).
Demand for medicinal plants is a major driver of species extinction — some of the most clinically effective medicinal plants are among the most threatened. Airmid provides the tools to understand and reduce environmental impact, identify cultivation alternatives to wild harvest, and comply with international trade regulations for protected species.
- IUCN Red List assessments: IUCN (International Union for Conservation of Nature) conservation status for 60+ medicinal plant species with quantitative IUCN criteria (population size, range size, decline rate) — Critically Endangered, Endangered, Vulnerable, Near Threatened, Least Concern.
- CITES trade restrictions: CITES (Convention on International Trade in Endangered Species) Appendix I (international trade prohibited — e.g., some Panax species), Appendix II (trade regulated by export permits), and Appendix III (trade restricted in specific countries).
- United Plant Savers: At-risk and to-watch species lists for North American medicinal plants — a more conservation-oriented list than IUCN, including species at risk from domestic harvesting pressure.
- Harvest sustainability: Maximum Sustainable Yield (MSY) calculations and wildcrafting guidelines for 40+ species — indicating what harvest level can be sustained without depleting wild populations.
- FairWild Standard compliance: FairWild Standard v2.0 compliance requirements and audit criteria — the international standard for verifying sustainable and equitable wild plant collection.
- Cultivation alternatives: Agronomic cultivation data for 35+ species including soil requirements, propagation methods, optimal growing conditions, yield per hectare, and economic viability of cultivation vs. wild harvest.
- Environmental footprint: Life Cycle Assessment-style quantification of carbon footprint (kg CO₂-eq), water footprint (liters per kg), land use, and biodiversity impact for 30+ species and sourcing methods.
- At-risk species substitution: Identify pharmacologically comparable substitutes for at-risk species — e.g., species with similar alkaloid profiles that are more abundantly cultivated.
15. AI and Machine Learning#
Machine learning capabilities for natural product drug discovery and evidence
synthesis (@airmid/ml).
Machine learning addresses two fundamental bottlenecks in phytotherapy research: the explosion of biomedical literature (too much for manual review) and the complexity of predicting molecular behavior from structure alone. Airmid's ML toolkit applies NLP to mine literature automatically and graph neural networks to predict compound properties from molecular graphs.
- Biomedical NLP: Named entity recognition (NER) with 200+ herb name patterns across multiple languages, 30+ relation extraction templates for herb-compound-target relationships, and automated population of the knowledge graph from literature.
- Automated systematic review screening: ML-powered abstract screening (ASReview-style active learning) that learns which papers are relevant and prioritizes the most likely-relevant abstracts for full-text review — dramatically accelerating systematic review processes.
- Knowledge graph population: Automated extraction and entity linking to populate the herb-compound-target-pathway-disease knowledge graph from PubMed abstracts and full texts.
- Graph Neural Networks (MPNN): Message Passing Neural Networks for molecular property prediction from molecular graph representations — each atom is a node, each bond is an edge, and information passes between connected nodes to predict properties.
- Atom featurization: 33-dimensional atom feature vectors for GNN input including atom type, hybridization, aromaticity, formal charge, ring membership, and H count.
- SMILES transformer: SMILES-based transformer encoder (~100 token vocabulary) treating SMILES sequences like language for compound property prediction.
- TransE knowledge graph embedding: Translational embeddings for link prediction in the herb-compound-disease knowledge graph — predicting missing relationships based on graph structure (e.g., predicting that a compound might be active against a disease it has not been tested against).
- RAG-style herbal medicine Q&A: Retrieval-augmented generation for grounded, evidence-cited answers to herbal medicine questions — each answer is supported by retrieved clinical evidence, not hallucinated by the model.
16. Computational Botany and Plant Vision#
AI-powered plant identification and morphological analysis (@airmid/vision).
Plant identification from photographs is a fundamental need for both professional botanical research and ensuring correct species use in herbal medicine. Misidentification of plant species is a documented cause of herb poisoning — water hemlock has been mistaken for edible umbellifers, and Digitalis for Symphytum. The vision module approaches identification through multiple morphological channels and combines their evidence Bayesianly for robust results.
- Leaf analysis: Leaf shape classification using EFDs (Elliptic Fourier Descriptors that capture the outline as a mathematical series) and Hu moment invariants, leaf margin classification (entire, serrate, dentate, lobed — using CCD frequency analysis of the margin contour), venation pattern recognition (pinnate, palmate, parallel), with 120+ species database.
- Flower analysis: Petal count, symmetry classification (actinomorphic/radially symmetric vs. zygomorphic/bilaterally symmetric), inflorescence type (raceme, panicle, umbel, capitulum, spike), petal fusion, ovary position (superior, inferior, half-inferior), with 60+ species floral formula database.
- Bark analysis: 12 bark texture types (smooth, furrowed, scaly, papery, peeling, plated, fibrous, corky, warty, ridged, lenticellate, shaggy), 50+ tree species bark reference database.
- Multi-organ species matching: Bayesian evidence combination from leaf, flower, bark, and fruit analyses — combining probability estimates from multiple organs for more reliable species identification than any single organ.
- Dichotomous key traversal: Guided dichotomous key for systematic plant identification — the traditional botanical identification method made interactive, leading users through yes/no decisions to a species identification.
- Toxic look-alike warnings: Alert when an identified species visually resembles a toxic species — e.g., water hemlock resembles edible umbellifer species.
- Geographic filtering: Filter identifications by geographic range across 14 WWF biomes and 100+ species distribution ranges — a plant only occurring in Asia cannot be correctly identified in Europe.
17. Clinical Integration#
Integration with clinical systems for point-of-care herbal medicine decision
support (@airmid/clinical).
Clinical integration is the layer that makes Airmid's scientific knowledge actionable in real healthcare settings. By speaking FHIR, LOINC, SNOMED CT, and CDS Hooks — the standard languages of electronic health records — Airmid can deliver herb-drug interaction alerts and evidence summaries directly into the clinician's workflow without requiring a separate lookup.
- FHIR R4 integration: HL7 FHIR (Fast Healthcare Interoperability Resources) R4 resource creation and parsing for interoperability with Electronic Health Record (EHR) systems — FHIR is the international standard for health data exchange.
- LOINC lab codes: 30+ LOINC (Logical Observation Identifiers Names and Codes) lab observation codes mapped to clinically relevant monitoring parameters — ALT, AST (liver function), creatinine, BUN (renal function), INR (coagulation), HbA1c (glucose control), potassium, and more.
- SNOMED CT herb codes: 20+ SNOMED CT (Systematized Nomenclature of Medicine Clinical Terms) concept codes for common medicinal herbs — enabling coding of herbal medicine use in clinical records.
- ICD-10-CM condition mapping: 25+ ICD-10-CM condition ranges that affect herb selection and safety — conditions that are contraindications, require dose adjustment, or influence herb choice.
- CDS Hooks integration: Clinical Decision Support Hooks response generation for real-time herb-drug interaction alerts, safety warnings, and evidence summaries at the point of prescribing in EHR systems.
- GRADE-rated evidence summaries: Evidence summaries with quantitative effect sizes for 20+ herb-indication pairs — formatted for clinicians who need actionable conclusions with uncertainty quantified.
- Point-of-care interaction checking: Real-time checking for herb-drug, herb-condition, herb-allergy, herb-lab (e.g., some herbs interfere with lab tests), and pregnancy interactions when a patient consults with concurrent herb and drug use.
18. Data Integration and APIs#
External bioinformatics database connectivity, ETL (Extract, Transform, Load)
pipelines, an OpenAPI 3.1 endpoint specification, and data export/reporting
(@airmid/api).
The @airmid/api library is the bridge between Airmid's internal knowledge base
and the broader bioinformatics ecosystem. It does not run an HTTP server;
instead, it provides the URL builders, parsers, pipeline framework, and OpenAPI
specification that consuming applications use to integrate with external
databases and expose Airmid data via REST. EXTERNAL_DATABASE_CONFIGS defines
connectors for 10 bioinformatics databases:
- PubMed/NCBI E-utilities: URL builders and parsers for PubMed literature search (esearch.fcgi, efetch.fcgi) with 3-requests/second (10/s with API key) rate-limit awareness.
- PubChem PUG REST: Chemical compound data from PubChem (compound/cid/{cid}/property/{props}/JSON) — the world's largest free chemistry database.
- ChEMBL REST: Bioactivity data from ChEMBL — the European database of drug-like molecules and their bioactivities against specific targets.
- UniProt REST: Protein sequence and functional annotation data — the gold standard protein sequence database.
- STRING API: Protein-protein interaction network data from STRING — the most widely used PPI database, covering known and predicted interactions.
- KEGG REST: Pathway and reaction data from the Kyoto Encyclopedia of Genes and Genomes — covering metabolic pathways, disease pathways, and drug information.
- DrugBank: Drug and drug-target reference data.
- ClinicalTrials.gov v2: Clinical trial registry data from the US National Library of Medicine's trial registry.
- WHO VigiBase: International pharmacovigilance adverse reaction data from the WHO global individual case safety report (ICSR) database.
- Natural Medicines Database: Commercial natural-product reference data.
Each connector ships URL builders, response parsers, and retry support (exponential backoff with jitter, retryable-error detection).
Public API Specification#
The @airmid/api library publishes a complete OpenAPI specification rather than
running a server — it defines the contract that a consuming service implements.
- OpenAPI 3.1 endpoint definitions:
AIRMID_API_ENDPOINTSdefines 44 REST endpoint specifications across 12 resource tags (Species, Compounds, Interactions, Evidence, Safety, Clinical, Targets, Pathways, Reports, Export, Webhooks, Admin).generateOpenAPISpec()assembles a complete OpenAPI 3.1 document. The library publishes the specification; it does not run an HTTP server. - 4 rate-limit tiers: free (100/day), basic (1K/day), pro (10K/day),
enterprise (effectively unlimited), with
checkRateLimitand request validation. - RFC 7807 errors and cursor pagination:
createProblemDetail/createValidationErrorforapplication/problem+jsonresponses;generateCursorPaginationfor base64-cursor pagination. - Webhooks and SDK generation:
WEBHOOK_SPECIFICATIONS(12 webhook event types) with HMAC-SHA256 signature verification;generateTypeScriptClientand code-example generation. - Multi-format export and reporting:
exportToJSON,exportToCSV(RFC 4180),exportToXML,exportToRDFTurtle,exportToSDF; 6 report templates; FAIR-compliance assessment.
ETL Pipelines#
The ETL pipeline framework keeps Airmid's knowledge base synchronized with upstream bioinformatics databases on defined schedules:
- 8 pre-defined scheduled pipelines: PubMed (weekly literature update), PubChem (monthly compound update), ChEMBL (monthly bioactivity update), ClinicalTrials.gov (weekly trial status update), UniProt (quarterly protein update), STRING (quarterly interaction update), KEGG (quarterly pathway update), VigiBase (monthly safety signal update).
- 18 transformation rules: CAS check digit validation, InChIKey format validation, SMILES canonicalization, species name resolution (40+ synonym-to-accepted-name mappings), and unit harmonization (converting from multiple reporting units to standard units).
- Exponential backoff with jitter: Robust retry logic for transient API failures — preventing cascade failures when upstream databases experience downtime.
19. SOTA Enhancement: Advanced AI/ML Technologies (Planned)#
State-of-the-art enhancements listed in TODOS.md phase 35.20 that represent the next frontier of Airmid's AI capabilities. All items in this section are planned, not yet implemented.
Large Language Models for Phytotherapy (planned)#
- TCMChat-style domain-specific LLM fine-tuning: Fine-tune LLMs on traditional Chinese medicine texts and modern phytotherapy literature for domain-specific reasoning that outperforms general models on herbal medicine questions.
- BERT-based named entity recognition: Specialized NER model for herbs, compounds, and diseases in biomedical text — outperforming general NER on the specific vocabulary of natural products science.
- GPT-powered evidence summarization: Automated summarization of multiple clinical trials into coherent evidence narratives for specific herb-indication pairs.
- Multi-lingual NLP for classical texts: Process Traditional Chinese Medical texts (Classical Chinese), Ayurvedic texts (Sanskrit), and Unani texts (Arabic/Persian) to extract traditional use data from primary sources.
- OpenTCM-style GraphRAG retrieval: Graph-augmented retrieval that traverses the herb-compound-target-disease knowledge graph to provide graph-structured evidence in answers.
- LLM hallucination detection: Detect and flag potentially hallucinated claims in LLM outputs in a medical context where incorrect information is dangerous.
Graph Neural Networks (planned)#
- GNN-based molecular property prediction: Message Passing Neural Network for predicting bioactivity, toxicity, and pharmacokinetic properties from molecular graphs.
- Graph attention network (GAT) for synergy prediction: Predict synergistic combinations of natural product compounds using attention-weighted graph convolutions.
- Heterogeneous GNN for multi-relational networks: Process the heterogeneous herb-compound-target-disease network with different node types and edge types simultaneously.
- Graph generative models for natural product-inspired design: Generate novel molecular scaffolds inspired by natural product structural motifs using generative graph models.
Transformer Models for Molecules (planned)#
- ChemBERTa molecular embeddings: Pre-trained transformer on SMILES strings for generating rich molecular representations used in property prediction tasks.
- MTL-BERT multi-task learning: Single transformer model that simultaneously predicts multiple molecular properties — ADMET, toxicity, bioactivity — sharing learned features across tasks.
- ToxBERT explainable toxicity prediction: Toxicity prediction model with attention-based explanations showing which molecular substructures drive the predicted toxicity.
Generative AI for Molecule Design (planned)#
- REINVENT 4 integration: De novo molecule generation with reinforcement learning-guided optimization toward user-specified property targets — generate novel natural product analogs with improved drug-likeness.
- Diffusion model for 3D molecular generation: Generate 3D molecular structures including 3D geometry (not just 2D connectivity) using diffusion models, enabling docking-ready molecule generation.
- Multi-objective ADMET optimization: Simultaneously optimize a generated molecule for multiple ADMET properties — increasing bioavailability while reducing toxicity, for example.