Production-grade, Groq-powered voice-to-prescription intelligence platform for multispeciality hospitals.
- Overview
- Core Features
- Tech Stack
- Project Architecture
- Module Documentation
- AI & Intelligence Layer
- Data Models
- Setup & Configuration
- Environment Variables
- Usage Guide
- UI Redesign Prompt (Stitch)
Hospital AI Clinical Assistant is a fully browser-based, zero-backend clinical documentation system designed for busy hospital doctors. It leverages Groq's LLaMA 3.1 8B Instant model to convert raw spoken doctor notes into structured, printable prescriptions β in real time.
The system works in two modes:
- Online Mode (Groq AI): Doctor speaks β Browser STT captures β Groq AI structures β Prescription generated
- Offline Mode (Local Parser): Zero API dependency, regex+NLP-based offline fallback with 250-medicine database
All data is stored in localStorage (HIPAA-style client-only, no server uploads).
- Uses Web Speech API (browser-native, no external SDK)
- Language set to
en-INfor Indian medical terminology - Continuous listening with 3-second silence detection auto-stop
- Real-time interim transcript display while speaking
- Stop/restart toggle with status indicators (idle / listening / processing)
- Model:
llama-3.1-8b-instant(ultra-fast inference) - Converts unstructured voice transcript β full structured clinical JSON
- Extracts: Patient Name, UHID, Age, Gender, Chief Complaint, Surgical History, Abdomen Examination, Palpable Abnormality, Radiology Impression, Provisional Diagnosis, Investigations Advised (Cardiac/Lab/Radiology), Management Plan, Medicines
- Handles phonetic errors (e.g., "Azy" β "Azithromycin", "Dolo" β "Dolo 650")
- Response format enforced as
json_objectfor zero-parse-failure - Temperature:
0.1for maximum clinical determinism
- 250-medicine database spanning all clinical categories
- 3-tier validation pipeline:
- Exact match (case-insensitive)
- Contains match (partial name match)
- Fuzzy match via Levenshtein distance (β€4 edits threshold)
- Each medicine gets a
validationbadge:β Verified/β οΈ Auto-corrected/β Not in DB
- Rich structured UI card with sections:
- Patient info (Name, UHID, Age)
- Clinical History (Chief Complaint, Surgical History)
- Examination (Abdomen, Palpable Abnormality)
- Radiology (Findings / Impression)
- Assessment (Diagnosis, Management Plan)
- Investigations (Cardiac / Lab / Radiology)
- Prescription Table (Medicine | Dosage | Frequency | Duration)
- Inline Edit Mode β doctor can edit any field directly in the card
- Export to Word (.doc) β generates professional letterhead HTML β
.docvia Blob API - Print to PDF β browser print dialog with print-optimized CSS
- Dual-bubble chat (Doctor bubble right, AI bubble left)
- Prescription cards rendered inline inside AI message thread
- Supports text input (keyboard) and voice input (mic button)
- File attachment button (UI ready, extendable)
- Error display bar with auto-dismiss
- Smooth scroll-to-latest using
useRef - Animated typing indicator while Groq processes
- Aggregates all consultations into unique patient records (deduplicated by UHID or name)
- Shows: Total Patients, Total Records, Active Today (live stat cards)
- Searchable by patient name or UHID
- Click "View Rx" β jumps directly to that consultation's chat
- Full CRUD on the medicine database:
- Add new medicine formulation
- Inline Edit existing medicine name
- Delete with confirmation
- Real-time search filter (250+ items)
- Changes persist to
localStorage - Toast notifications for success/error states
- Hospital Profile: Edit institutional name (reflected everywhere in the UI)
- AI Integration: Securely paste/update Groq API key (masked password input)
- Danger Zone: Factory reset β clears all localStorage consultation data
- Sticky Save bar at the bottom
- Accessible from the Chat header Settings icon
- Key format validation (
gsk_prefix check) - Key stored in
localStorageonly (never sent to any server except Groq's own endpoint) - Show/hide password toggle
- Links directly to
console.groq.com/keys
- All consultations stored in
localStorageas JSON (hospital_consultations) - Sidebar groups consultations as Today vs Previous
- Click any consultation β restores full chat + prescriptions
- New Consultation button starts a fresh session
- Hospital name and API key also persist across page reloads
- Zero-dependency fallback when no API key is configured
- Extracts via regex patterns:
- Patient name (supports Mr/Mrs/Miss/Dr prefixes)
- UHID from "UHID:", "Patient ID:", "PID:"
- Age from "age 45", "45 years old"
- Gender from gendered pronouns & keywords
- Symptoms from 35+ keyword dictionary
- Medicines directly from 250-medicine database scan
- Dosage (mg/ml/mcg/tab/cap), Frequency, Duration
generateDocument()creates plain-text formatted prescription
- Sidebar hidden on mobile, slides in via
transform/translate - Mobile hamburger menu toggles sidebar
- Backdrop blur overlay on mobile sidebar open
- All views (Chat, Directory, Inventory, Settings) fully mobile-responsive
| Layer | Technology | Purpose |
|---|---|---|
| Framework | React 18.2 + Vite 5.2 | SPA, fast HMR dev |
| Styling | TailwindCSS 3.4 | Utility-first responsive design |
| Animation | Framer Motion 11 | Page transitions, card animations |
| Icons | Lucide React | Consistent medical + UI icons |
| AI Engine | Groq Cloud (LLaMA 3.1 8B) | VoiceβJSON prescription extraction |
| STT | Web Speech API (browser native) | Real-time voice transcription |
| Storage | localStorage | Client-only data persistence |
| Build | Vite + @vitejs/plugin-react | Fast build + JSX transform |
| Linting | ESLint + react-hooks plugin | Code quality |
hospital-assistant/
βββ src/
β βββ App.jsx # Root β state, routing, persistence
β βββ main.jsx # React DOM entry
β βββ index.css # Global styles + Tailwind directives
β β
β βββ components/
β β βββ Sidebar.jsx # Left nav: consultations + module links
β β βββ ChatInterface.jsx # Main doctor-AI chat + voice input
β β βββ PrescriptionCard.jsx # Rich clinical report card + export
β β βββ PatientDirectory.jsx # Patient list with stats + search
β β βββ MedicineInventory.jsx # CRUD medicine database manager
β β βββ Settings.jsx # Hospital config + API key + danger zone
β β βββ ApiKeyModal.jsx # Groq key input modal
β β
β βββ utils/
β β βββ groqApi.js # Groq API calls (extract + document gen)
β β βββ medicineValidator.js # 3-tier fuzzy medicine validation
β β βββ prescriptionParser.js # Offline regex-based transcript parser
β β
β βββ data/
β βββ medicines.js # 250-medicine curated database
β
βββ public/
βββ vite.config.js
βββ tailwind.config.js
βββ package.json
βββ README.md
- Manages top-level state:
apiKey,hospitalInfo,medicines,consultations,currentConsultationId,view - All state persists to
localStorageviauseEffect - Routes between 4 views:
chat,directory,medicines,settings - Passes
onUpdateConsultationhandler to ChatInterface for history sync
- State:
micStatus,transcript,inputText,prescriptions,messages,metadata,errorMsg - Web Speech API lifecycle:
startListening()βonresult(interim) β 3s silence βstopListening()βprocessAndSend() processAndSend(text):- Appends doctor message to thread
- Calls
extractPrescriptionFromSpeech()(Groq) orparseTranscript()(offline) - Appends AI reply +
PrescriptionCardto thread - Updates metadata (patient name, diagnosis)
- Syncs back to history via
onUpdateHistory()
groqRequest(apiKey, system, user)β generic Groq fetch with JSON response formatextractPrescriptionFromSpeech(transcript, apiKey, medicineList)β primary extraction- Injects hospital medicine list into system prompt for phonetic correction
- Validates returned medicines via
validateMedicines()
generatePrescriptionDocument(structuredData, hospitalName, apiKey)β formats plain text document
levenshtein(a, b)β O(mΓn) DP string distancevalidateMedicine(input)β 3-tier: exact β contains β Levenshtein (β€4)validateMedicines(array)β maps validation over AI medicine array
parseTranscript(transcript)β full offline extraction pipelinegenerateDocument(data, hospitalName)β plain text prescription formatter
Endpoint : https://api.groq.com/openai/v1/chat/completions
Model : llama-3.1-8b-instant
Temp : 0.1 (deterministic for medical accuracy)
Format : json_object (guaranteed JSON output)
The system prompt instructs the model to:
- Output ONLY valid JSON (no markdown, no prose)
- Use
nullfor missing fields - Fix phonetic errors by mapping to the injected medicine list
- Extract comprehensive clinical fields from single voice input
{
"patient_name": "string | null",
"age": "number | null",
"gender": "string | null",
"uhid": "string | null",
"chief_complaint": "string",
"past_history": {
"surgical_history": "string",
"duration": "string"
},
"clinical_examination": {
"abdomen": "string",
"palpable_abnormality": "string"
},
"radiology": {
"findings": "string",
"impression": "string"
},
"provisional_diagnosis": "string",
"investigations_advised": {
"cardiac": ["string"],
"laboratory": ["string"],
"radiology": ["string"]
},
"plan": "string",
"medicines": [
{
"name": "string",
"dosage": "string",
"frequency": "string",
"duration": "string"
}
]
}{
id: 1712345678901, // timestamp as unique ID
patient_name: "Ramesh Patel",
diagnosis: "Acute Appendicitis",
messages: [
{ role: "doctor" | "ai", content: "...", type?: "prescription", prescriptionData?: {} }
],
prescriptions: [
{ id: 1712345678902, data: { ...prescriptionJSON } }
]
}{
name: "Dolo", // raw AI output
dosage: "650mg",
frequency: "Twice Daily",
duration: "5 days",
validation: {
matched: "Dolo 650", // corrected name from DB
status: "fuzzy", // valid | fuzzy | invalid
original: "Dolo"
}
}- Node.js 18+
- npm or yarn
- Groq API key (free at console.groq.com/keys)
# Clone / open project
cd hospital-assistant
# Install dependencies
npm install
# Start development server
npm run dev
# Production build
npm run build- App runs at
http://localhost:5173 - Click the βοΈ Settings icon in the chat header
- Enter your Groq API key (
gsk_...) - Start speaking! Press the π€ microphone button
Create a .env file in the project root (optional):
# If set, this key is pre-loaded (user can still override via UI)
VITE_GROQ_API_KEY=gsk_your_key_hereNote: Without a key, the app automatically falls back to the offline regex parser. No functionality is broken β the offline mode still extracts medicines, patient details, and generates prescriptions.
- Click "New Consultation" in the sidebar
- Press the π€ microphone button (turns red when listening)
- Speak naturally: "Patient Ramesh Patel, age 58, male, UHID 12345. Chief complaint chest pain for 3 days. Past surgical history appendectomy 2 years ago. Abdomen soft. No palpable abnormality. USG shows impression of kidney stone. Provisional diagnosis acute cholecystitis. Advise CBC, LFT, USG abdomen. Prescribe Pantoprazole 40mg once daily for 7 days, Buscopan twice daily for 5 days."
- Stop talking β 3-second silence auto-submits
- Prescription card appears instantly
- Click "Edit Report" on any prescription card
- All fields become editable inline
- Click "Finish Editing" to save
- Word (.doc): Generates professional letterhead document
- Print PDF: Browser print dialog with clinic-ready layout
- Go to Medicine Inventory from the sidebar
- Search, add, edit, or remove medicines
- Changes immediately affect AI phonetic correction
- All data is client-side only β no server, no database, no cloud storage
- The Groq API key is stored in
localStorageβ remind users this is their own browser - The offline parser is a robust fallback but Groq AI provides far superior accuracy
- The medicine database can be expanded by adding entries to
src/data/medicines.js - For production deployment, consider adding HTTPS + CSP headers for security
Built with β€οΈ for clinical excellence