Module, AI & Decision Support

AI &
Decision Support

The AI module brings artificial intelligence into every corner of the hospital—from a ChatGPT-style assistant that answers clinical questions to a SQL agent that builds reports from plain English, a live Command Center that monitors operations, predictive models that forecast patient volumes and risks, and prescriptive tools that optimize scheduling, beds, and staffing.

What is AI in HMIS?

The AI module is a complete artificial intelligence platform embedded inside the hospital management system. It connects to multiple AI providers(like OpenAI, Anthropic, or local models) through a unified AI Gateway, so the system isn't locked into any one vendor.

The module powers AI Chat (a conversational assistant that can run live database queries), AI SQL Assistant / SQL Forge (turns plain English into safe read-only database queries using the shared Prisma schema catalog), a Role & Permissions Advisor (audits roles against the live matrix and recommends nodes for billing, IPD visits, inventory PO/GRN, HR policies, and more), a Command Center dashboard with live operational metrics and AI-generated briefs, Predictive Analytics(readmission risk, length-of-stay, demand forecasting, anomaly detection),Prescriptive AI (smart scheduling, resource optimization, staffing recommendations), and Usage Logging that tracks every AI interaction for audit, cost tracking, and quality improvement.

There are also over 20 clinical AI tools built into specific workflows: clinical summaries, lab result insights, appointment prep briefs, draft clinical notes, diet allergy audits, pharmacy reorder analysis, vitals trend narratives, and more.

Why Does It Exist?

  • → Clinical decision support — Doctors can ask the AI for drug interactions, treatment guidelines, or diagnostic suggestions. The AI analyzes the patient's records and provides evidence-based insights.
  • → Operational efficiency — Managers can ask "How many patients were admitted last week?" in plain English. The AI turns this into a safe SQL query, runs it against the live database, and shows the results with optional charts.
  • → Predictive insight — AI can forecast busy days (demand forecasting), identify patients at risk of readmission, predict length-of-stay, and flag anomalies in lab results.
  • → Democratized data access — Non-technical staff (nurses, administrators) can ask questions about data and get answers without needing a data analyst or knowing SQL.
  • → Safety-first architecture — Every AI feature is permission-gated, SQL queries run in READ ONLY transactions with a timeout, and all interactions are logged for audit.

Who Uses This Module?

Doctors & Clinicians

Ask clinical questions, get AI-generated patient summaries, draft notes, lab insights, differential diagnosis prompts, and prescription clarity checks

Hospital Administrators

Run operational queries, view command center dashboards, generate reports, forecast demand, optimize schedules and staffing

IT & System Admins

Configure AI providers, monitor usage and costs, review audit logs, manage permissions, and tune model settings

Architecture

The AI Gateway

Every AI feature flows through a single AI Gateway—a unified abstraction layer that sits between the HMIS and multiple AI providers. This means the hospital is never locked into one vendor.

1

Provider Abstraction Layer

The AI Gateway supports OpenAI, Anthropic, and local/open-source models. Each request is routed to the best provider based on the task type — clinical questions get a medical-grade model, report-building gets a code-capable model, and simple queries use a fast, low-cost model. Providers are configured via environment variables.

Behind the scenes: Configuration is managed through environment variables (HMIS_AI_PROVIDER, OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.). The system checks `hasAnyAiProvider()` before every AI route and returns a friendly 'AI not configured' message if no provider is set up.
2

Permission System

The AI module has 7 distinct permissions: `ai:clinical` (clinical AI tools), `ai:operational` (operations briefs), `ai:chat` (chat assistant), `ai:sql-query` (SQL query access), `ai:predictive` (predictive analytics), `ai:prescriptive` (prescriptive optimization), and `ai:admin` (AI administration & usage). Some tools require multiple permissions (e.g., a lab insight needs both `ai:clinical` and `lab:view`).

Behind the scenes: Permissions are checked using `requirePermission()` and `requireAllPermissions()` middleware. For example, reading a patient's AI summary requires `patients:view`, `clinical:view`, AND `ai:clinical`. The Chat route checks for `ai:chat` OR `ai:clinical`.
3

SQL Safety Layer (Critical)

When the AI generates SQL queries to answer user questions, it passes through <strong>three layers of protection</strong>: (1) <strong>Validation</strong> &mdash; the SQL is parsed by `node-sql-parser` and checked against an allowlist of ~80 clinical/financial tables; sensitive tables like `users`, `refresh_tokens`, `audit_logs` are blocked. (2) <strong>READ ONLY transaction</strong> &mdash; the query runs inside a database-enforced read-only transaction; any INSERT/UPDATE/DELETE fails automatically. (3) <strong>Statement timeout</strong> &mdash; queries are killed after 10 seconds to prevent runaway queries.

Behind the scenes: The safety layer also blocks: forbidden keywords (INSERT, UPDATE, DELETE, DROP, TRUNCATE, ALTER, CREATE, GRANT, etc.), SQL comments (an obfuscation channel), multiple statements (semicolons), sensitive columns (password, secret, token_hash), and SELECT...INTO TABLE. AI SQL runs on the main database with application-layer validation plus a READ ONLY transaction barrier.
4

Audit & Usage Logging

Every AI interaction is logged. The `AiUsageLog` table records: who made the request, which provider was used, the tool path, latency in milliseconds, success/failure status, and error messages. For AI chat sessions, messages are stored with full metadata including SQL results, chart specs, and presentation modes.

Behind the scenes: Usage logs power the AI admin dashboard (cost tracking by provider, token counts, latency averages). A separate `aiPrediction` table stores predictive analytics results with risk scores, confidence levels, and explanations. Admins can view usage summaries grouped by provider with total requests, input/output tokens, cost estimates, and latency.
Deep Dive

How AI Chat Works

The AI Chat is the most powerful tool. It's not just a chatbot — it can understand data requests, run safe SQL queries against the live database, and present results as tables or charts.

1

User Asks a Question

The user types a question in plain English, like 'How many patients were admitted this week?' or 'Show me the top 5 doctors by number of appointments this month.' The question is sent to the `/api/v1/ai/chat/` endpoint with the session context.

Behind the scenes: Each chat session is stored in the `aiChatSession` table. Messages are stored in `aiChatMessage` with role (user/assistant), content, and metadata. Sessions support pagination (GET /sessions) and can be deleted.
2

Data Query Detection

The system analyzes the user's message for data-seeking intent. It checks against 50+ keywords ('how many', 'list', 'show me', 'total', 'chart', 'name', 'MRN') and patterns (detail intent, follow-up intent, patient lookups). If the message looks like a data query and the user has `ai:sql-query` + global record scope, the AI SQL Agent is invoked.

Behind the scenes: The `runSqlAgent()` function is the core. It uses a retry loop (up to 3 attempts) that sends the prompt + schema to the AI, validates the generated SQL, and executes it. If the SQL fails validation or execution, it retries with the error message as context for the AI to fix itself.
3

SQL Agent Execution

The SQL Agent receives: the user's question, the database schema context, and the conversation history (for follow-ups like 'show their details'). The AI generates a PostgreSQL SELECT query. The query is safety-validated, capped at 500 rows + 1 for truncation detection, and executed in a READ ONLY transaction with a 10-second timeout.

Behind the scenes: The schema context describes ~80 tables (patients, appointments, invoices, lab reports, etc.) plus relationships. The safety validator uses `node-sql-parser` to parse the SQL into an AST and checks every referenced table against an allowlist. Sensitive tables (users, audit_logs, refresh_tokens) are blocked.
4

Response with Results & Charts

SQL results are normalized and passed to the AI for natural language response. The system also auto-infers chart specs (bar, line, pie, etc.) based on the data shape. The UI receives: the AI's text response, the raw results, chart configuration, presentation mode, and row count. Results are cached in chat metadata for history.

Behind the scenes: The `inferSqlChartSpec()` function analyzes the result columns to determine if they should be displayed as a table, bar chart, line chart, pie chart, or metric card. The `inferChatPresentation()` function decides the best UI mode. The metadata is stored as `SanitizedAiChatMetadata` with summary-only persistence (full row data is not persisted to protect privacy).
Operations Hub

Command Center & Live Map

The Command Center provides a real-time operational snapshot of the entire hospital. It shows 10 live zones with status indicators (normal / warning / critical), plus an AI-generated brief that summarizes the current state.

Emergency

Active ER cases

Critical when ER is full; shows patients waiting for a bed

Bed Occupancy

Occupied / Total beds

Critical at ≥95%, Warning at ≥80% occupancy

OPD Today

Today's appointments

Warning when >40 patients still booked

Lab Queue

Pending lab orders

Critical at >50, Warning at >25 pending orders

Radiology

Pending radiology studies

Warning at >15 pending studies

OT Schedule

Today's surgeries

Purely informational, no threshold-based alerts

Ambulance

Ambulances in transit

Warning when >3 ambulances en route

Inpatients

Currently admitted

Warning when admissions exceed available beds

Billing

Unpaid invoices

Warning at >30 unpaid/partial invoices

Stock Alerts

Low-stock SKUs

Warning at >10 items below reorder level

Deep Dive

Every Feature Explained

AI Chat Assistant

What it is

A conversational assistant that answers clinical and operational questions. It can run live SQL queries against the database, present results as tables or charts, and maintain multi-turn conversations.

Why it exists

Gives every staff member instant access to hospital data without needing to learn SQL or navigate complex screens.

How it works

The chat endpoint accepts messages + session ID. If the user asks a data question (detected by 50+ keywords + pattern matching) and has SQL permissions, the AI SQL Agent generates and runs a safe query. Results are shown inline with auto-inferred charts.

AI SQL Assistant

What it is

Describe the report you want in plain English. The AI generates a PostgreSQL query, validates it for safety, runs it, and returns results with optional charts.

Why it exists

Non-technical staff can create custom reports without learning SQL. The safety layer ensures no data can be damaged.

How it works

POST to `/api/v1/ai/sql-query/` with your question. The AI generates SQL from the shared Prisma schema catalog (same tables as Report Builder and SQL Chat), which is parsed and validated (READ ONLY enforcement, timeout). Results are normalized, chart specs are inferred, and everything is logged.

Role & Permissions Advisor

What it is

Chat assistant that audits roles against the live permission matrix and recommends missing or extra nodes.

Why it exists

Admins need help mapping duties (billing edit, IPD visits, PO/GRN, HR policies, machine integration) to exact permission names.

How it works

Roles Info → Role Advisor (roles:manage or ai:admin). Context includes every active role's grants, the full permission catalog (ALL_APP_PERMISSIONS union DB), and module/table knowledge from Prisma. Supports @Role mentions. Endpoints: POST /api/v1/ai/role-advisor and /role-advisor/stream.

Command Center

What it is

A live dashboard showing 10 operational zones (ER, beds, OPD, lab, radiology, OT, ambulance, billing, inventory) with status indicators and AI-generated briefs.

Why it exists

Gives management a real-time view of the entire hospital. Spot bottlenecks before they become crises.

How it works

The `loadCommandCenterMap()` function queries 15+ database tables to build a live snapshot. The map shows zones with normal/warning/critical status based on configurable thresholds. An optional AI brief (`/brief` endpoint) generates a natural language summary of the current state.

Clinical Patient Summary

What it is

AI generates a concise summary of a patient's recent clinical records, including symptoms, diagnoses, prescriptions, and notes.

Why it exists

Doctors can get up to speed on a patient's history in seconds instead of reading through pages of notes.

How it works

POST to `/clinical-summary` with a patient ID (requires `patients:view`, `clinical:view`, `ai:clinical`). The system fetches the latest 25 clinical records and sends them to the AI for summarization. Results are saved as AI tool runs for future reference.

Lab Result Insights

What it is

AI analyzes lab test results and provides an understandable interpretation of the findings.

Why it exists

Lab reports can be complex. AI helps clinicians quickly understand what the numbers mean and flag abnormalities.

How it works

POST to `/lab-insights` with a test order ID (requires `lab:view`, `ai:clinical`). The system fetches the order and latest lab report, then sends the result data to the AI for analysis. The AI provides a plain-language interpretation.

Appointment Prep Brief

What it is

Before a patient appointment, the AI generates a prep brief summarizing the patient's recent history, diagnoses, and previous visit notes.

Why it exists

Clinicians can walk into each appointment already informed, saving time and improving care quality.

How it works

POST to `/appointment-prep` with an appointment ID (requires `ai:clinical` + appointment permissions). The system fetches the appointment details, patient info, and last 3 clinical records, then generates a concise prep summary.

Clinical Draft Assistant

What it is

AI reviews a draft clinical note and suggests improvements, additional details, or corrections.

Why it exists

Helps clinicians write better, more complete clinical notes. Reduces documentation errors.

How it works

POST to `/clinical-draft-assist` with your draft text and optional patient ID (requires `clinical:view`, `ai:clinical`). The AI can also incorporate the patient's last 5 records for context-aware suggestions.

SOAP clinical note scribe

What it is

Opt-in browser Web Speech dictation or paste encounter notes; AI drafts a structured SOAP note for clinician review. Session mode accumulates segments before drafting. Not ambient room capture.

Why it exists

Speeds documentation after visits without inventing diagnoses.

How it works

POST to `/clinical-note-draft` with `transcript` and optional `patientId` (requires `clinical:view`, `ai:clinical`). Patient chart: SOAP scribe control; mic uses browser speech + `/speech-translate` and stops on blur/silence.

Discharge summary draft

What it is

Drafts an inpatient discharge summary from admission metadata, clinical notes, and linked services.

Why it exists

Gives clinicians a starting discharge narrative to edit before paperwork.

How it works

POST to `/discharge-summary-draft` with `admissionId` (requires `clinical:view`, `ai:clinical`, and `admissions:view` or `admissions:manage`). Shown on the patient chart and as AI draft on the admissions discharge dialog.

Report Builder AI summary

What it is

Summarizes Report Builder preview grids, full CSV exports, and scheduled deliveries into bullets and caveats, or finance/dashboard insight snapshots into a short narrative.

Why it exists

Helps staff interpret ad-hoc report results, exported CSVs, and period insights without reading every row.

How it works

POST to `/report-summary` with capped columns/sample rows or a finance/dashboard context (requires `ai:reports:summarize` or `ai:clinical`/`ai:operational`/`ai:admin`; Report Builder also needs `reports:builder`; finance narrative needs a finance AI grant). Preview button on Report Builder results + Finance Insights; full export requests `aiSummary: true` and reads `X-HMIS-Ai-Summary*` headers; scheduled runs soft-summarize when the creator holds the summarize pack.

Document OCR / PDF extract

What it is

Extracts text from chart PDFs or raster images and optionally structures it with AI. Image OCR runs locally with Tesseract.

Why it exists

Turns referral/lab PDFs and photographed documents into readable Markdown without retyping.

How it works

POST to `/document-ocr` with `mediaAttachmentId`, `pdfBase64`, or `rawText` (requires `ai:documents:ocr` or `ai:clinical`). Chart Documents supports PDF, PNG, JPEG, WebP, BMP, and TIFF extraction; lab PDF upload auto-fills `reportMarkdown` when text is extractable. Image-only pages embedded inside PDFs are not rendered for OCR yet.

Predictive: Readmission Risk

What it is

AI estimates the probability that a patient will be readmitted within 30 days of discharge.

Why it exists

Hospitals are penalized for high readmission rates. Early identification allows preventive interventions.

How it works

The AI analyzes admission history (up to 12 records), recent vitals (20 readings), and clinical diagnoses (15 notes). It returns a JSON with: risk score (0-1), confidence level, contributing factors, and clinical rationale. Results are stored in the `aiPrediction` table.

Predictive: Length of Stay

What it is

Predicts how many days a patient is likely to stay in the hospital based on their admission data.

Why it exists

Helps with bed planning, staffing, and resource allocation.

How it works

The AI analyzes the admission record (ward, bed, reason, current status). Returns expected length-of-stay in days with confidence and contributing factors. Uses JSON mode with structured output.

Predictive: Demand Forecast

What it is

Forecasts patient volume for a specific department and date range.

Why it exists

Helps hospitals prepare for busy periods, schedule staff, and manage supplies.

How it works

The AI analyzes historical appointment counts (last 90 days by status) plus currently scheduled appointments in the target window. Returns forecasted visits, peak days, and assumptions. Configured with low AI temperature (0.3) for consistent results.

Predictive: Anomaly Detection

What it is

AI reviews lab results for unusual patterns that may warrant clinical review.

Why it exists

Critical abnormalities can be missed in busy labs. AI provides a second line of defense.

How it works

The AI analyzes recent lab test orders (up to 25) with their result data. Returns flagged anomalies with severity (low/medium/high), descriptions, and an overall summary. Does not diagnose &mdash; just flags items for review.

Prescriptive: Smart Scheduling

What it is

AI proposes an optimized appointment schedule for a doctor, reducing gaps and overload.

Why it exists

Poor scheduling leads to long patient wait times and frustrated doctors. AI can find optimal patterns.

How it works

The AI analyzes the doctor's existing appointments in the date range, their availability, and their specialization. Returns recommendations, suggested time blocks, and risk factors. Requires `ai:prescriptive` permission plus appointment view permissions.

Prescriptive: Resource Optimization

What it is

AI analyzes bed utilization and OT room usage to suggest operational improvements.

Why it exists

Beds and OT rooms are expensive resources. Optimizing their use saves money and reduces wait times.

How it works

The AI reviews bed counts by status, OT room statuses/types, and recent surgery volume (last 7 days). Returns improvements, bed/OT-specific actions, and a summary with confidence level.

Prescriptive: Staffing Recommendations

What it is

AI recommends staffing adjustments based on historical demand patterns.

Why it exists

Understaffing leads to burnout; overstaffing wastes money. AI helps find the right balance.

How it works

The AI analyzes appointment volumes and statuses over the last ~8 weeks. Returns role-specific FTE recommendations (nurses, clerks, clinicians) with rationale and confidence.

Operational Briefs

What it is

AI generates executive-level briefs on hospital operations: census, capacity, shift handoff, billing, pharmacy reorders, schedule pulse, and clinical feed.

Why it exists

Leaders need quick, digestible overviews of hospital status without combing through multiple dashboards.

How it works

Each brief type (`/operational-brief`, `/census-brief`, `/shift-handoff-brief`, `/billing-brief`, `/pharmacy-reorder-brief`, `/schedule-pulse`, `/clinical-feed-sync`) fetches a targeted data snapshot and sends it to the AI for natural language summarization.

Usage Logging & Administration

What it is

Complete audit trail of all AI usage. Tracks who used what, which provider, latency, success/failure, tokens, and cost estimates.

Why it exists

Ensures accountability. Helps track AI costs across providers. Identifies training needs or misconfigurations.

How it works

Every AI route calls `logAiUsage()` which writes to `aiUsageLog`. Admins (with `ai:admin`) can view paginated usage logs, grouped by provider with aggregates (total requests, input/output tokens, cost estimates, average latency). Usage summary provides totals and per-provider breakdown.

Real-World Example

“Busy Monday Morning”

It's Monday morning. The hospital administrator opens the Command Center dashboard and sees the ER zone is critical(15 active cases, 3 waiting for a bed), the lab queue is warning(35 pending orders), and bed occupancy is at 91%. She clicks the AI Brief button, and the system generates a summary:

"ER is at critical capacity with 15 active cases and 3 patients waiting for inpatient beds. Lab turnaround is slowing — 35 orders pending. Recommend opening the overflow ER bay and assigning one additional phlebotomist. Bed occupancy at 91% (48/53); consider expediting 5 pending discharges."

The administrator then asks the AI Chat: "Show me today's admissions by department." The AI detects this as a data query, generates a safe SELECT with JOINs across patients, admissions, and beds, executes it in a READ ONLY transaction, and presents the results as a bar chart. She sees that IPD admitted 8 patients, ICU admitted 3, and 2 are still waiting for bed assignments.

Measurable Impact

  • Real-time Visibility

    10 operational zones with live status updates. The command center map regenerates on every request by querying 15+ tables.

  • Zero Data Loss

    AI-generated SQL runs in READ ONLY transactions. Even if the SQL model hallucinates a DELETE, the database prevents it.

  • Multi-Provider Flexibility

    Configure OpenAI, Anthropic, local models, or any combination. The AI Gateway routes requests by task type.

  • Full Audit Trail

    Every AI interaction is logged with user, provider, latency, and success/failure. Admins can analyze usage and costs.

AI & Decision
Architecture

The AI module is built on three database tables plus a provider-agnostic gateway. Every interaction is permission-gated, safety-checked, and audited.

Technical Architecture

FieldTypeInstitutional Role
prompt_text / user_inputTextThe natural language question or command the user typed.
response_text / outputTextThe AI-generated response, summary, SQL, or prediction result.
model_used / providerVarchar(64)The AI provider that processed the request (openai, anthropic, local).
response_time_ms / latency_msIntTime taken for the AI to process and respond, in milliseconds.
tokens_consumedIntInput and output token counts used for cost tracking and optimization.
permission_checkVarchar(32)The RBAC permission gate that was verified before processing the request.
cost_estimateDecimalEstimated cost of the AI API call, calculated from token counts and provider pricing.
success / error_messageBoolean / TextWhether the AI request succeeded, plus the error message if it failed.
risk_score / confidenceDecimal(0-1)For predictions: the risk/score (0-1) and AI's confidence in its prediction.
chart_specJSONAuto-inferred chart configuration (bar, line, pie, metric) for data result visualization.

Note: Sensitive fields use AES-256 field-level encryption where applicable.

Governance & Power

ai:clinical
ai:operational
ai:chat
ai:sql-query
ai:predictive
ai:prescriptive
ai:admin

AI Gateway Providers

The AI Gateway abstracts away individual providers. Configured via environment variables, it supports OpenAI, Anthropic, and local models through the free-flow client. The primary provider and fallbacks are managed through the gateway.

Provider-agnostic: swap models without code changes
  • SQL Safety Architecture

    Three-layer protection: (1) node-sql-parser AST validation against allowlist, (2) READ ONLY transaction (DB-enforced write barrier), (3) 10-second statement timeout. Uses the main DATABASE_URL with no separate readonly clone.

  • Permission Matrix

    7 AI-specific permissions plus module-specific gates (e.g., lab insight requires ai:clinical + lab:view). Chat requires ai:chat OR ai:clinical. SQL query requires explicit ai:sql-query grant.

  • Prompt Window Safety

    All user prompts and context are bounded using `boundPromptWindow()` to prevent token overflow. System prompts include strict formatting instructions to prevent prompt injection.

  • Auto-Save & History

    Every AI tool run is auto-saved via `autoSaveAiRun()` with the tool path, label, request payload, output, and provider. Users can browse their history, search by tool or label, and re-run previous queries.

  • Metrics & Observability

    Prometheus metrics track AI request duration and total count by provider and outcome (success/error). Combined with Loki logging and Grafana dashboards for full observability.