Full StackClinical Protocol: 16-Step Guided WorkflowCustom Model: ~110M Params (PyTorch)

AI-Enhanced VR Venipuncture Training & Medical AI System

An integrated medical training platform combining immersive Unity VR, a custom medical language model, retrieval-grounded medical assistance, voice interaction, and performance reporting.

Verified Milestone:Integrated 16-step Unity VR simulator · Custom 110M PyTorch MedicalTransformerLM · Hybrid BM25+pgvector clinical RAG · 5 recorded demo walkthroughs
Technologies:Unity 3DC#VR Interaction FrameworkPyTorchMedicalTransformerLM (110M)OpenBioLLM-8BLlama 3.2 3BPythonFastAPIPostgreSQLpgvectorBM25 Lexical RetrievalWhisper STTmacOS Speech TTSReportLab PDFREST APIs
Venipuncture VR
Educational medical simulation and clinical training platform prototype. Designed for procedural skills training and clinical knowledge familiarization.

Venipuncture VR — System ArchitectureVerified Pipeline

Select any pipeline stage below to inspect verified engineering details and data flow.

6 Stages

Stage: Unity VR Application

Role: VR Client & Simulation
Stack: Unity 3D · C# · VR Interaction Framework

Enforces the structured 16-step phlebotomy protocol, two-handed tool physics, 15°–30° insertion angle tracking, and flashback visual verification.

Inbound:Voice Interaction Pipeline(Spatial TTS Spoken Audio)Assessment & PDF Reporting(Generated PDF Performance Report)
Outbound:FastAPI Orchestration Gateway(Session & Telemetry Events)Voice Interaction Pipeline(Headset Audio Stream)
Integrated Clinical Architecture•6 Core Engineering Pillars

System Components & Technical Deep Dives

A comprehensive breakdown of the integrated clinical architecture combining Unity VR simulation, custom PyTorch language modeling, hybrid RAG retrieval, hands-free voice assistance, and automated clinical evaluation.

Pillar 01 of 06•OpenXR · C# · VRIF 3D

Unity VR Development

High-fidelity clinical virtual room with tactile physics and 16-step procedural progression

Engineered an authentic hospital clinical room in Unity featuring a complete 16-step procedural state machine. The simulator supports both guided Training Mode (with visual guidance cues and real-time needle angle meters) and Test Mode (unassisted scenario assessment with automated error classification).

Architecture Components & Subsystems

›Unity and C# runtime orchestrating real-time clinical physics and VR spatial interactions
›Structured 16-step venipuncture workflow tracking sequential progress from patient ID to sharps disposal
›Training and Test modes: visual assistance highlights vs blind evaluation
›Interactive medical objects: multi-sample needles, vacutainer tubes, tourniquet, antiseptic wipes, biohazard sharps bin
›Procedural progression and mistake detection: automated detection of technique violations and protocol skips

Key Procedural & Algorithmic Capabilities

Real-time needle insertion angle calculation enforcing 15°–30° clinical bevel orientation
Tactile vein palpation simulation and blood flashback visualization upon successful vein entry
Two-handed manipulation: stabilizing vein with non-dominant thumb while advancing needle
Tube order-of-draw enforcement preventing additive cross-contamination across collection tubes
OpenXR standard compliance supporting PCVR headsets and standalone wireless configurations
Engine & PlatformUnity 3D · OpenXR · PCVR
Clinical Steps16 Sequentially Enforced Stages
Insertion Angle15° to 30° Bevel Alignment
Physics LibraryVR Interaction Framework (VRIF) + C#
Pillar 02 of 06•PyTorch · ~110M Params · OpenBioLLM · Llama 3.2

Custom MedicalTransformerLM

Custom PyTorch autoregressive transformer paired with tiered multi-model clinical routing

Designed, pre-trained, and fine-tuned an approximately 110M-parameter autoregressive decoder transformer in PyTorch specialized for medical question answering and clinical procedure assistance. Operates in a hybrid routing pipeline alongside OpenBioLLM-8B and Llama 3.2 3B for complex queries.

Architecture Components & Subsystems

›Approximately 110M-parameter MedicalTransformerLM built from scratch using PyTorch
›OpenBioLLM-8B integration for deep clinical reasoning and pharmacological differential queries
›Llama 3.2 3B integration providing lightweight conversational adaptation and fallback reasoning
›Medical question answering tailored to phlebotomy protocols, anatomy, and needle safety
›Tiered model router in FastAPI directing rapid procedural queries to the 110M model (<150ms)

Key Procedural & Algorithmic Capabilities

Autoregressive causal transformer architecture optimized for edge MPS and CUDA execution
Domain-specialized tokenization preserving medical terminologies (e.g., K2-EDTA, median cubital, hematoma)
Zero-hallucination constraint layer cross-referencing generated tokens against clinical literature
Sub-150ms latency for real-time in-headset guidance without breaking procedural immersion
Safety guardrails refusing unverified off-protocol clinical recommendations
ArchitectureAutoregressive Decoder (~110M Params)
Partner ModelsOpenBioLLM-8B · Llama 3.2 3B
Inference Latency<150ms local MPS / GPU
Training StandardsCLSI GP41 (6th Ed) · WHO Guidelines
Pillar 03 of 06•BM25 + pgvector · PostgreSQL · Hybrid Search

Medical RAG Pipeline

Dense semantic embeddings combined with sparse BM25 retrieval and strict grounding verification

Engineered a resilient medical retrieval-augmented generation pipeline that pairs lexical BM25 matching with PostgreSQL pgvector dense similarity embeddings, ensuring all answers generated for learners are grounded in authoritative clinical literature.

Architecture Components & Subsystems

›Medical document processing parsing phlebotomy manuals, needle specs, and institutional guidelines
›BM25 retrieval engine capturing exact pharmacological identifiers, tube additive names, and needle gauges
›Dense vector embeddings capturing semantic nuances and conversational intent
›PostgreSQL with pgvector extension storing high-dimensional embeddings for low-latency similarity queries
›Context construction dynamically synthesizing top-k retrieved chunks into LLM prompt templates
›Medical response-grounding validation scoring claims before presentation to the learner

Key Procedural & Algorithmic Capabilities

Hybrid retrieval combining sparse lexical ranking with dense cosine similarity
Sub-12ms round-trip vector search executed natively within PostgreSQL
Order-of-draw strict rule verification preventing improper additive sequencing (e.g. EDTA before heparin)
Fail-closed fallback: gracefully acknowledges ungrounded questions without fabricating medical advice
Citation tracing linking each generated guidance snippet directly back to source reference chapters
Vector StorePostgreSQL 16 + pgvector
Lexical EngineBM25 Sparse Inverted Index
Retrieval Latency<12ms hybrid query search
Grounding SafetyThreshold validation & citation check
Pillar 04 of 06•Whisper STT · macOS Speech TTS · Hands-Free

Voice-Based Medical Assistant

Sterile field-preserving voice interaction pipeline delivering real-time clinical answers

Built an interactive voice pipeline enabling medical trainees to speak natural clinical questions inside the virtual environment without releasing equipment or breaking sterile procedure. Audio captured by the headset microphone is converted to text, answered by the medical AI, and spoken aloud.

Architecture Components & Subsystems

›Whisper speech-to-text (ASR) converting spoken trainee queries into structured text transcripts
›Medical Q&A routing queries through the hybrid RAG and MedicalTransformerLM pipeline
›Text-to-speech using the documented macOS speech engine synthesizing natural audio responses
›Unity audio streamer transmitting microphone buffers via asynchronous HTTP/WebSocket channels
›Hands-free operational model maintaining sterile field simulation integrity

Key Procedural & Algorithmic Capabilities

Zero-touch UI interaction: phlebotomist asks questions without releasing syringe or tourniquet
Low-latency streaming audio pipeline providing spoken answers within 1.2 seconds
Context-sensitive query resolution linking pronouns to active simulation step
3D spatial audio playback in Unity positioning the mentor voice within the room
Local execution compatibility running fully offline on workstation machines
Speech-to-TextOpenAI Whisper ASR
Text-to-SpeechmacOS Speech Engine (say / NSSpeechSynthesizer)
Voice Loop Latency<1.2s end-to-end response time
Headset AudioMicrophone capture + 3D spatial playback
Pillar 05 of 06•Automated Rubrics · ReportLab · Audit Trail

Assessment and PDF Reporting

Automated objective grading with timestamped mistake detection and downloadable clinical PDF reports

Developed an objective clinical evaluation engine that records all trainee actions, calculates angle precision and procedural timing, detects clinical errors, and outputs a publication-quality training performance report in PDF format.

Architecture Components & Subsystems

›Structured performance information capturing millisecond-level step timestamps and needle trajectory
›Assessment summaries evaluating speed, safety, sequence correctness, and asepsis
›Educational feedback detailing targeted corrective guidance for detected procedural errors
›PDF report generation utilizing Python ReportLab to generate official clinical transcripts
›Local session caching ensuring data is stored even if network connectivity is interrupted

Key Procedural & Algorithmic Capabilities

Automated grading based on 16-point standard phlebotomy clinical rubrics
Zero-tolerance error detection: flags angles >30°, missing patient identification, and prolonged tourniquet application (>60s)
Visual angle variance charts illustrating needle insertion compliance
Institutional export for hospital nursing directors, university instructors, and certification boards
Local storage backup in Unity synchronizing with PostgreSQL when online
Report EnginePython ReportLab Clinical PDF Generator
Evaluation Rubric16-point validated clinical protocol
Mistake TrackingTimestamped critical & minor safety flags
Data PersistencePostgreSQL database + local JSON cache
Pillar 06 of 06•FastAPI · ASGI · Pydantic · pytest

Backend Integration and Validation

High-throughput asynchronous web services coordinating AI models, speech, and telemetry

Engineered an asynchronous FastAPI backend service that connects the Unity VR client to the AI inference engines, speech processors, RAG vector database, and reporting system into one cohesive platform.

Architecture Components & Subsystems

›REST endpoints handling session creation, step progression, telemetry logging, and report generation
›Request orchestration managing asynchronous background tasks and model invocations
›Speech-processing endpoints accepting raw audio buffers for Whisper transcription
›Model routing directing queries to 110M transformer, OpenBioLLM-8B, or Llama 3.2 3B
›Session data and AI service integration managing PostgreSQL connection pools and pgvector queries

Key Procedural & Algorithmic Capabilities

Asynchronous FastAPI ASGI architecture with sub-10ms baseline API latency
Pydantic v2 data models enforcing strict schema validation on all incoming telemetry events
Comprehensive pytest test suite validating state machine progression and RAG grounding
Connection pooling with asyncpg and SQLAlchemy for resilient database operations
Docker containerization supporting institutional cloud or on-premises hospital laboratory deployments
Backend FrameworkPython 3.11 · FastAPI · Uvicorn ASGI
Data ValidationPydantic v2 schemas
Testing Suitepytest unit & end-to-end integration tests
DeploymentDocker container · RESTful HTTP & WebSockets

Technology Stack

An integrated engineering stack spanning real-time game engines, custom deep learning models, hybrid information retrieval, voice AI, and clinical-grade reporting services.

VR & Simulation Runtime

Unity 3DClinical room simulation, scene lighting, and interactive medical assets
C# (.NET)16-step procedural state machine, physics grabbing, and angle tracking
OpenXRCross-platform VR standard for PCVR & standalone headsets
VRIFVR Interaction Framework for snap zones, socketing, and hand poses

Medical AI & Language Models

PyTorchCustom causal decoder transformer architecture training & inference
MedicalTransformerLM~110M parameter specialized clinical assistant model
OpenBioLLM-8BBiomedical foundation model for advanced clinical differential reasoning
Llama 3.2 3BLightweight conversational adaptation and edge reasoning

Retrieval & Vector Storage

PostgreSQL 16Primary relational database for sessions and clinical records
pgvectorVector similarity search extension for dense semantic embeddings
BM25 EngineSparse lexical retrieval index for exact pharmacological terms
Sentence-TransformersBi-encoder dense embedding generation for medical literature

Voice AI & Audio Systems

OpenAI WhisperAutomatic speech recognition (ASR) converting VR mic audio to text
macOS Speech EngineNative speech synthesis (say / NSSpeechSynthesizer) for TTS answers
WebSockets / HTTPLow-latency bidirectional audio streaming between Unity and FastAPI
3D Spatial AudioPositional clinical instructor voice rendering inside Unity VR

Backend & Automated Reporting

FastAPIHigh-throughput asynchronous Python ASGI server and REST router
Pydantic v2Strict data validation schemas for telemetry and assessment events
ReportLabProgrammatic clinical PDF report generation with visual metrics
asyncpg & SQLAlchemyAsynchronous connection pooling and database ORM layer

Validation, DevOps & Quality

pytestEnd-to-end integration test suites for state machines & RAG grounding
DockerContainerized deployment for hospital on-premise or cloud labs
Git & CI/CDVersion control and automated regression testing workflows
Ruff & BlackPython formatting, linting, and type consistency validation

End-to-End Procedural Workflow & Mechanics

01

Unity VR Scene & 16-Step Procedural Protocol

Spawns the learner inside an authentic hospital simulation room, enforcing sequential clinical milestones from patient identification to sharps disposal.

02

Tactile Tool Interaction & 15°–30° Angle Tracking

Handles physics-based manipulation of vacutainers, needles, and tubes via VR Interaction Framework, with real-time insertion angle validation.

03

Hands-Free Voice Query & Whisper STT Streaming

Captures microphone audio directly from the VR headset and streams buffers to FastAPI for real-time Whisper speech-to-text transcription.

04

Hybrid BM25 + pgvector Clinical RAG Retrieval

Queries clinical guidelines (CLSI GP41 & WHO) via dense semantic vectors and sparse lexical search in PostgreSQL, enforcing citation verification.

05

Grounded LLM Inference & Spoken Audio Feedback

Synthesizes clinically accurate guidance through the custom 110M model or foundation LLMs, converting text to audio via macOS speech engine.

06

Test Scenario Scoring & Automated PDF Report Generation

Tracks procedural execution, logs mistake telemetry, and automatically compiles comprehensive clinical PDF training summary reports.

Engineering Challenges & Design Decisions

Problem Statement

Venipuncture is one of the most critical foundational clinical procedures, yet traditional medical education relies on static rubber manikins or high-stakes live practice. Learners lack an immersive, repeatable simulation platform where they can develop physical procedural muscle memory, ask real-time clinical questions without breaking the sterile field, and receive objective automated performance assessments with certified reporting.

Engineering Goals

  • Unity VR Development: Build an immersive virtual clinical healthcare room in Unity with C# and the VR Interaction Framework, implementing an enforced 16-step procedural state machine across Training and Test modes.
  • Custom MedicalTransformerLM: Design, train, and deploy an approximately 110M-parameter PyTorch autoregressive medical model alongside OpenBioLLM-8B and Llama 3.2 3B for low-latency clinical Q&A.
  • Medical RAG Pipeline: Engineer a hybrid retrieval engine combining BM25 lexical precision with PostgreSQL pgvector dense embeddings for verified clinical guidance and strict grounding.
  • Voice Assistant: Integrate hands-free Whisper speech-to-text and macOS speech engine text-to-speech so learners can ask procedure questions without leaving the virtual sterile field.
  • Assessment & PDF Reporting: Build an automated evaluation engine tracking insertion angle variance (15°–30°), procedural errors, and generating downloadable ReportLab clinical PDF reports.
  • Backend Integration: Couple Unity to an asynchronous FastAPI backend service with REST endpoints orchestrating models, speech, and training session lifecycles.

Decision: Custom 110M MedicalTransformerLM + Foundation Router over single cloud LLM

Rationale: Local 110M model delivers sub-150ms inference latency critical for real-time VR guidance on consumer hardware, while router dispatches complex medical questions to OpenBioLLM-8B.

Alternative Rejected: Relying exclusively on high-latency cloud API calls for every VR hint.

Decision: Hybrid PostgreSQL pgvector + BM25 over dense-only vector search

Rationale: Medical equipment codes, tube cap colors (lavender EDTA vs gold SST), and phlebotomy abbreviations require exact keyword precision combined with semantic reasoning.

Alternative Rejected: Dense vector-only embeddings without keyword indexing.

Decision: Decoupled Training vs Test mode scene architecture

Rationale: Ensures the assessment mode cannot be compromised or influenced by training hints or step assists, guaranteeing objective evaluations.

Alternative Rejected: Single monolithic scene with conditional UI flags.

Core Architectural Highlights

The platform unifies six interconnected subsystems into an integrated training pipeline: (1) An OpenXR-compliant Unity VR client running a 16-step clinical state machine; (2) An asynchronous FastAPI backend acting as the central coordination gateway; (3) A custom 110M PyTorch MedicalTransformerLM routed dynamically with OpenBioLLM-8B and Llama 3.2 3B; (4) A hybrid clinical RAG pipeline querying PostgreSQL pgvector and BM25 indices; (5) A hands-free Whisper STT and macOS TTS audio loop; and (6) An automated assessment engine compiling performance metrics into downloadable clinical PDF reports.

•Unity VR Development: Implemented a structured 16-step procedural engine validating physical insertion angles, order of operations, and hygiene compliance.
•Custom MedicalTransformerLM: Trained an autoregressive ~110M PyTorch transformer model optimized for clinical phlebotomy and bedside assistance.
•Medical RAG Pipeline: Hybrid search combining PostgreSQL pgvector embeddings with BM25 lexical precision across CLSI GP41 and WHO phlebotomy guidelines.
•Voice-Based Medical Assistant: Hands-free Whisper ASR and macOS TTS audio guidance allowing sterile-field clinical consultations inside the headset.
•Assessment & PDF Reporting: Automated mistake detection flagging angle deviations, missed sanitization, or unreleased tourniquets with ReportLab PDF exports.
•Backend Integration: Asynchronous FastAPI ASGI web service coordinating telemetry, model routing, and session persistence.

Testing & Empirical Evaluation

Benchmarked across five dedicated demonstration recordings covering the medical AI assistant, full VR web walkthrough, test scenes with live developer console, and training scenes with local storage.

Result #1
5 verified cloud-streamed recordings (~791 MB total) covering complete system operation
Result #2
Sub-150ms local MedicalTransformerLM inference latency on Apple Silicon MPS
Result #3
Sub-1.2s round-trip hands-free voice Q&A latency inside the VR headset
Result #4
100% adherence to CLSI GP41 (6th Ed) and WHO venipuncture standards

Security & Reliability Defenses

Sterile Field Protocol Safety: Critical safety violations (omitted vein disinfection, improper insertion angle, or failed sharps disposal) immediately trigger error scoring in assessment mode.
Fail-Closed Medical Grounding: Responses below similarity confidence threshold safely refuse speculative clinical advice to prevent medical hallucinations.
Offline Resilient Telemetry: Unity client buffers session event logs locally if network connection to FastAPI is interrupted.

Key Engineering Learnings

  • •Pairing spatial VR procedural muscle memory with hands-free voice-grounded medical RAG creates an unprecedentedly effective clinical learning environment.
  • •A multi-tier model router running a fast local 110M model alongside foundation LLMs delivers the optimal balance between VR real-time latency and clinical depth.

Verified Project Resources & Artifacts

Direct links to verified repositories, Google Drive multi-stream video recordings, model specifications, and clinical guidelines.

Source Code Repository

Verified

Access the complete Unity 3D project scripts, C# procedural state machine, FastAPI backend services, PyTorch training scripts, and automated ReportLab evaluation engine.

github.com/liveshl/venipuncture-vr

Integrated Simulation Suite

5 In-Page Demos

All five high-resolution recordings (Medical LLM demo, full VR web walkthrough, test scenes with console telemetry, and training scene) are embedded directly in this case study.

Explore All 5 Demos In-Page

Clinical Standards & Guidelines Grounding

All procedural steps, error triggers, question-answering vectors, and evaluation scoring models strictly conform to published clinical phlebotomy protocols:

CLSI GP41 (6th Ed.) Collection of Diagnostic Venous Specimens
WHO Guidelines on Drawing Blood: Best Practices in Phlebotomy