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
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.
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.
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`).
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> — 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> — the query runs inside a database-enforced read-only transaction; any INSERT/UPDATE/DELETE fails automatically. (3) <strong>Statement timeout</strong> — queries are killed after 10 seconds to prevent runaway queries.
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.
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.
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.
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.
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.
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.
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.
Active ER cases
Critical when ER is full; shows patients waiting for a bed
Occupied / Total beds
Critical at ≥95%, Warning at ≥80% occupancy
Today's appointments
Warning when >40 patients still booked
Pending lab orders
Critical at >50, Warning at >25 pending orders
Pending radiology studies
Warning at >15 pending studies
Today's surgeries
Purely informational, no threshold-based alerts
Ambulances in transit
Warning when >3 ambulances en route
Currently admitted
Warning when admissions exceed available beds
Unpaid invoices
Warning at >30 unpaid/partial invoices
Low-stock SKUs
Warning at >10 items below reorder level
Every Feature Explained
AI Chat Assistant
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.
Gives every staff member instant access to hospital data without needing to learn SQL or navigate complex screens.
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
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.
Non-technical staff can create custom reports without learning SQL. The safety layer ensures no data can be damaged.
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
Chat assistant that audits roles against the live permission matrix and recommends missing or extra nodes.
Admins need help mapping duties (billing edit, IPD visits, PO/GRN, HR policies, machine integration) to exact permission names.
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
A live dashboard showing 10 operational zones (ER, beds, OPD, lab, radiology, OT, ambulance, billing, inventory) with status indicators and AI-generated briefs.
Gives management a real-time view of the entire hospital. Spot bottlenecks before they become crises.
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
AI generates a concise summary of a patient's recent clinical records, including symptoms, diagnoses, prescriptions, and notes.
Doctors can get up to speed on a patient's history in seconds instead of reading through pages of notes.
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
AI analyzes lab test results and provides an understandable interpretation of the findings.
Lab reports can be complex. AI helps clinicians quickly understand what the numbers mean and flag abnormalities.
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
Before a patient appointment, the AI generates a prep brief summarizing the patient's recent history, diagnoses, and previous visit notes.
Clinicians can walk into each appointment already informed, saving time and improving care quality.
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
AI reviews a draft clinical note and suggests improvements, additional details, or corrections.
Helps clinicians write better, more complete clinical notes. Reduces documentation errors.
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
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.
Speeds documentation after visits without inventing diagnoses.
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
Drafts an inpatient discharge summary from admission metadata, clinical notes, and linked services.
Gives clinicians a starting discharge narrative to edit before paperwork.
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
Summarizes Report Builder preview grids, full CSV exports, and scheduled deliveries into bullets and caveats, or finance/dashboard insight snapshots into a short narrative.
Helps staff interpret ad-hoc report results, exported CSVs, and period insights without reading every row.
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
Extracts text from chart PDFs or raster images and optionally structures it with AI. Image OCR runs locally with Tesseract.
Turns referral/lab PDFs and photographed documents into readable Markdown without retyping.
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
AI estimates the probability that a patient will be readmitted within 30 days of discharge.
Hospitals are penalized for high readmission rates. Early identification allows preventive interventions.
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
Predicts how many days a patient is likely to stay in the hospital based on their admission data.
Helps with bed planning, staffing, and resource allocation.
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
Forecasts patient volume for a specific department and date range.
Helps hospitals prepare for busy periods, schedule staff, and manage supplies.
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
AI reviews lab results for unusual patterns that may warrant clinical review.
Critical abnormalities can be missed in busy labs. AI provides a second line of defense.
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 — just flags items for review.
Prescriptive: Smart Scheduling
AI proposes an optimized appointment schedule for a doctor, reducing gaps and overload.
Poor scheduling leads to long patient wait times and frustrated doctors. AI can find optimal patterns.
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
AI analyzes bed utilization and OT room usage to suggest operational improvements.
Beds and OT rooms are expensive resources. Optimizing their use saves money and reduces wait times.
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
AI recommends staffing adjustments based on historical demand patterns.
Understaffing leads to burnout; overstaffing wastes money. AI helps find the right balance.
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
AI generates executive-level briefs on hospital operations: census, capacity, shift handoff, billing, pharmacy reorders, schedule pulse, and clinical feed.
Leaders need quick, digestible overviews of hospital status without combing through multiple dashboards.
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
Complete audit trail of all AI usage. Tracks who used what, which provider, latency, success/failure, tokens, and cost estimates.
Ensures accountability. Helps track AI costs across providers. Identifies training needs or misconfigurations.
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.
“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
| Field | Type | Institutional Role |
|---|---|---|
| prompt_text / user_input | Text | The natural language question or command the user typed. |
| response_text / output | Text | The AI-generated response, summary, SQL, or prediction result. |
| model_used / provider | Varchar(64) | The AI provider that processed the request (openai, anthropic, local). |
| response_time_ms / latency_ms | Int | Time taken for the AI to process and respond, in milliseconds. |
| tokens_consumed | Int | Input and output token counts used for cost tracking and optimization. |
| permission_check | Varchar(32) | The RBAC permission gate that was verified before processing the request. |
| cost_estimate | Decimal | Estimated cost of the AI API call, calculated from token counts and provider pricing. |
| success / error_message | Boolean / Text | Whether the AI request succeeded, plus the error message if it failed. |
| risk_score / confidence | Decimal(0-1) | For predictions: the risk/score (0-1) and AI's confidence in its prediction. |
| chart_spec | JSON | Auto-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:clinicalai:operationalai:chatai:sql-queryai:predictiveai:prescriptiveai:adminAI 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.
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.