AI-Powered Virtual Simulated Patients for Mental Health Interview Training
Practice psychiatric interviewing skills with realistic AI-powered virtual patients and receive instant feedback on your performance.
Features β’ Quick Start β’ Documentation β’ API Docs
- Overview
- Features
- Technology Stack
- Quick Start
- Detailed Setup
- Project Structure
- API Documentation
- Usage Guide
- Research Background
- Cost Optimization
- Contributing
- Troubleshooting
- License
VSP MVP is a full-stack web application that provides AI-powered virtual simulated patients for training mental health professionals. Students can conduct realistic psychiatric interviews and receive automated evaluations based on 8 core competencies.
- π For Students: Practice psychiatric interviews anytime, anywhere without hiring actors
- π¨ββοΈ For Educators: Scale clinical training with consistent, evidence-based evaluations
- π₯ For Institutions: Supplement clinical training programs cost-effectively with virtual simulations
- Adapted from peer-reviewed research (CureFun paper, arXiv:2404.13066v2)
- Specialized for mental health education (not general medicine)
- Comprehensive evaluation on psychiatric interviewing competencies
- Real-time conversation with contextual AI responses
- Complete audit trail with conversation history
- Natural conversational interactions using GPT-4o-mini
- Emotionally authentic responses matching mental health conditions
- Context-aware dialogue with conversation memory
- Role consistency (patient never acts as clinician)
8 Core Competencies (0-10 scale each):
- Rapport Building & Therapeutic Alliance
- Active Listening & Empathy
- Psychiatric History Taking
- Risk Assessment (suicide/homicide screening)
- Biopsychosocial Assessment
- Communication Skills
- Cultural Sensitivity & Respect
- Interview Structure & Completeness
Non-Scoring Metrics (CureFun methodology):
- Information Density (medical terminology usage)
- Emotional Tendency (communication warmth)
- Response Length (average message length)
- Turn Number (conversation exchanges)
Built-in Cases (4 mental health conditions):
- Major Depressive Disorder
- Generalized Anxiety Disorder
- Post-Traumatic Stress Disorder (PTSD)
- Bipolar Disorder
Admin Features:
- Create custom cases via web UI
- Edit existing cases
- Set difficulty levels
- Define expected questions
- Custom prompt templates
3 User Roles:
- Student: Conduct interviews, receive evaluations
- Evaluator: View all evaluations and conversations
- Admin: Full access including case and user management
Features:
- Secure authentication (NextAuth + JWT)
- Role-based access control (RBAC)
- User approval workflow
- Conversation history per student
- Permanent storage of all conversations
- View full transcripts with timestamps
- Export transcripts as text files
- Link conversations to evaluations
- Evaluator access to all student conversations
- Framework: FastAPI (Python 3.10+)
- LLM: OpenAI GPT-4o-mini via LangChain
- Database: PostgreSQL with SQLAlchemy ORM
- Migrations: Alembic
- Authentication: JWT tokens, bcrypt password hashing
- Framework: Next.js 14 (React 18, TypeScript)
- Styling: Tailwind CSS with dark mode
- Authentication: NextAuth.js
- HTTP Client: Axios
- UI Icons: Lucide React
- Containerization: Docker & Docker Compose
- Development: Hot reload for both frontend and backend
- API Docs: Auto-generated Swagger/OpenAPI
- Node.js 18+ and npm
- Python 3.10+
- PostgreSQL 14+
- OpenAI API Key (required)
git clone <repository-url>
cd vsp-mvp# Copy example files
cp env.example .env
# Backend environment
cd backend
cp .env.example .env
# Edit backend/.env and add your OpenAI API key
# Frontend environment
cd ../frontend
cp .env.example .env.local
# Edit frontend/.env.local
cd ..Minimum Required in backend/.env:
LLM_PROVIDER=openai
OPENAI_API_KEY=sk-your-actual-openai-key-here
OPENAI_MODEL=gpt-4o-mini
DATABASE_URL=postgresql://vsp_dummy_user:password@localhost:5432/vsp_dummy
NEXTAUTH_SECRET=your-random-secret-here
NEXTAUTH_URL=http://localhost:3000Minimum Required in frontend/.env.local:
NEXT_PUBLIC_API_URL=http://localhost:8000
NEXTAUTH_SECRET=your-random-secret-here
NEXTAUTH_URL=http://localhost:3000# Create PostgreSQL database
createdb vsp_dummy
# Run migrations
cd backend
source venv/bin/activate # or venv\Scripts\activate on Windows
pip install -r requirements.txt
alembic upgrade headcd backend
python -m scripts.create_adminOption A: Using Docker (Recommended)
docker-compose up --buildOption B: Local Development
# Terminal 1 - Backend
cd backend
source venv/bin/activate
cd ..
python -m uvicorn backend.main:app --reload --port 8000
# Terminal 2 - Frontend
cd frontend
npm install
npm run dev- Frontend: http://localhost:3000
- Backend API: http://localhost:8000
- API Docs: http://localhost:8000/docs
See detailed guides:
- SETUP_GUIDE.md - Complete setup instructions
- DATABASE_SETUP.md - Database configuration
- QUICK_START.md - Quick reference guide
- PAPER_ALIGNMENT.md - Research methodology
vsp-mvp/
βββ backend/ # FastAPI backend
β βββ alembic/ # Database migrations
β βββ ai/ # LangChain AI layer
β β βββ chains/ # LangChain chains
β β β βββ patient_chain.py # Patient simulation
β β β βββ evaluation_chain.py # Evaluation chain
β β βββ memory/ # Conversation memory
β β βββ prompts/ # Prompt templates
β βββ core/ # Core configuration
β β βββ config.py # Settings (LLM, DB, etc.)
β β βββ auth.py # Authentication logic
β β βββ llm_client.py # LLM client initialization
β βββ models/ # SQLAlchemy models
β β βββ user.py # User model
β β βββ case_db.py # Case model
β β βββ evaluation.py # Evaluation model
β β βββ chat_history_db.py # Chat history model
β βββ routers/ # API endpoints
β β βββ auth.py # Authentication endpoints
β β βββ cases.py # Case management
β β βββ chat.py # Chat & conversation endpoints
β β βββ evaluate.py # Evaluation endpoints
β βββ services/ # Business logic
β β βββ chat_service.py # Chat orchestration
β β βββ evaluation_service.py # Evaluation logic
β β βββ metrics_service.py # Non-scoring metrics
β βββ data/cases/ # Case definitions (JSON)
β βββ main.py # FastAPI app entry point
βββ frontend/ # Next.js frontend
β βββ app/ # App router pages
β β βββ page.tsx # Homepage
β β βββ chat/ # Interview page
β β βββ results/ # Evaluation results
β β βββ history/ # Student history
β β βββ conversation/ # Transcript viewer
β β βββ auth/ # Sign in/up pages
β β βββ admin/ # Admin pages
β βββ lib/ # Utilities
β β βββ api.ts # API client
β β βββ errorMessages.ts # Error handling
β βββ providers/ # React providers
βββ docker-compose.yml # Docker configuration
βββ README.md # This file
GET /api/cases/summaryReturns aggregated case information without sensitive details.
Response:
{
"total_cases": 4,
"difficulty_counts": {
"easy": 1,
"medium": 2,
"hard": 1
},
"categories": ["Depression", "Anxiety", "PTSD", "Bipolar Disorder"]
}POST /api/auth/register- User registrationPOST /api/auth/login- User loginGET /api/auth/me- Current user info
GET /api/cases/- List all cases (full details)GET /api/cases/{case_id}- Get specific casePOST /api/cases/- Create case (admin only)PUT /api/cases/{case_id}- Update case (admin only)DELETE /api/cases/{case_id}- Delete case (admin only)
POST /api/chat/- Send message to patientPOST /api/chat/end-session- End conversationGET /api/chat/conversations- Get student's conversationsGET /api/chat/conversations/{chat_id}- Get full transcriptGET /api/chat/admin/conversations- Get all conversations (evaluator)
POST /api/evaluate/- Evaluate conversationGET /api/evaluate/- List evaluations (evaluator)GET /api/evaluate/{evaluation_id}- Get specific evaluation
GET /api/users/- List all usersPUT /api/users/{user_id}/approve- Approve userPUT /api/users/{user_id}/role- Update user role
Full API Documentation: http://localhost:8000/docs (when running)
- Sign Up: Create an account at
/auth/signup - Browse Cases: View available cases on homepage
- Start Interview: Click "Start Interview" on any case
- Conduct Interview: Ask questions naturally, as you would in a real clinical setting
- End Interview: Click "End Interview" when finished
- Review Results: View your scores, strengths, and areas for improvement
- View History: Access past conversations at
/history - Review Transcripts: Click on any conversation to see full transcript
- View All Conversations: Access
/admin/conversations - Filter by Case: Use filters to find specific conversations
- Review Transcripts: View full conversation details
- Access Evaluations: Link directly to evaluation results
- Monitor Progress: Track student performance over time
- Manage Users: Approve new users, assign roles at
/admin/users - Create Cases: Add new patient cases at
/cases/create - Edit Cases: Update existing cases
- Monitor System: Access all evaluator features plus case management
This project implements the methodology from the CureFun paper:
"Leveraging Large Language Model as Simulated Patients for Clinical Education"
Li, Y., Zeng, C., Zhong, J., Zhang, R., Zhang, M., & Zou, L. (2024)
arXiv preprint arXiv:2404.13066v2
- Domain: Physical medicine β Mental health
- Focus: Medical history β Psychiatric interviewing
- Risk Assessment: Added suicide/homicide screening
- Evaluation: Adapted criteria for mental health context
See PAPER_ALIGNMENT.md for detailed methodology alignment.
The system defaults to GPT-4o-mini for optimal cost-effectiveness:
| Model | Cost per Interview | Monthly Cost (5000 interviews) |
|---|---|---|
| GPT-4o-mini β | $0.018 | $90 |
| GPT-3.5-turbo | $0.024 | $120 |
| GPT-4 | $0.36 | $1,800 |
Savings: 95% cost reduction vs GPT-4 with comparable quality
Set in backend/.env:
OPENAI_MODEL=gpt-4o-mini # Default in codeFor hybrid approach (GPT-4o-mini for chat, GPT-4 for evaluation), modify service classes to use different models.
graph LR
Student[Student Browser] --> Frontend[Next.js Frontend]
Frontend --> Backend[FastAPI Backend]
Backend --> LLM[OpenAI GPT-4o-mini]
Backend --> DB[(PostgreSQL)]
Backend --> Memory[LangChain Memory]
LLM --> PatientSim[Patient Simulation]
LLM --> Evaluation[Evaluation]
- Student selects a case and starts interview
- Frontend sends message to backend API
- Backend retrieves conversation context from memory
- LangChain constructs prompt with case data + history
- OpenAI generates patient response
- Backend saves message to database and memory
- Frontend displays response to student
- On interview end: Evaluation runs and scores performance
users
- User accounts with roles (admin, evaluator, student)
- Authentication and authorization data
cases
- Patient case definitions
- Can supplement JSON case files
evaluations
- Student evaluation results
- Linked to students and sessions
chat_history
- Full conversation transcripts
- Permanent storage with timestamps
- Linked to students and cases
# Check current version
cd backend
alembic current
# Apply all migrations
alembic upgrade head
# Rollback one migration
alembic downgrade -1-
Homepage (Unauthenticated):
- View case count and categories (no sensitive details)
- Sign in to access full cases
-
Homepage (Authenticated):
- Browse all available cases with full details
- Filter by difficulty level
- Start interviews immediately
-
Chat Interface:
- Real-time conversation with virtual patient
- Message history with auto-scroll
- Visual loading indicators
- End interview button
-
Results Page:
- Detailed score breakdown with visualizations
- Strengths and areas for improvement
- Narrative feedback from AI evaluator
- Conversation analytics
-
History Page:
- List of all past conversations
- Message counts and duration
- Links to transcripts and evaluations
-
Transcript Viewer:
- Full conversation replay
- Color-coded messages
- Export functionality
- Timestamp display
- User Management: Approve users, assign roles
- Case Management: Create, edit, delete cases
- Conversation Dashboard: View all student conversations
- Evaluation Access: Review all assessments
- Filtering & Search: Find specific conversations or students
- β Password hashing with bcrypt
- β JWT token authentication
- β Role-based access control (RBAC)
- β CORS configuration
- β SQL injection prevention (SQLAlchemy ORM)
- β Input validation (Pydantic models)
- β Authorization checks on all protected endpoints
- Enable HTTPS
- Add rate limiting
- Implement session expiration
- Set up audit logging
- Configure CSP headers
- Add input sanitization for case creation
- Implement GDPR compliance (data retention)
-
Unauthenticated User:
- Visit homepage β should see case summary (not full details)
- Try to access
/chatβ should redirect to sign-in
-
Authenticated Student:
- Browse full case list
- Start interview and send messages
- End interview and receive evaluation
- View history and transcripts
-
Admin/Evaluator:
- Access user management
- View all conversations
- Create new cases
Create test accounts using the admin script:
cd backend
python -m scripts.create_admin --email student@test.com --username student --password test123Cause: Backend not running or wrong API URL
Solution:
# Check backend is running on port 8000
curl http://localhost:8000/health
# Verify NEXT_PUBLIC_API_URL in frontend/.env.localCause: NextAuth token expired or invalid
Solution:
- Sign out and sign in again
- Verify NEXTAUTH_SECRET matches in both backend/.env and frontend/.env.local
- Clear browser cookies for localhost
Cause: Network error or API unreachable
Solution:
- Check backend is running:
curl http://localhost:8000/health - Check CORS settings in backend/core/config.py
- Verify firewall not blocking localhost
# Reset database (β οΈ WARNING: Deletes all data)
cd backend
alembic downgrade base
alembic upgrade headGemini quota exceeded:
- Set
LLM_PROVIDER=openaiin backend/.env - Restart backend server
OpenAI authentication failed:
- Verify API key is valid
- Check key has not expired
- Ensure API key has sufficient credits
- Homepage load: < 1 second
- Case list (authenticated): < 500ms
- Chat message: 2-4 seconds (LLM generation)
- Evaluation: 5-8 seconds (LLM analysis)
- Transcript view: < 1 second
- In-memory session storage (consider Redis for production)
- Database indexes on session_id, student_id, case_id
- Pagination recommended for >100 conversations
- Connection pooling configured (SQLAlchemy)
- Create a feature branch
- Make changes with clear commit messages
- Test thoroughly (authentication, roles, error cases)
- Submit pull request with description
- Python: Follow PEP 8, use type hints
- TypeScript: Use ESLint configuration
- React: Functional components with hooks
- CSS: Use Tailwind utility classes
New Case:
- Create JSON file in
backend/data/cases/ - Or use admin UI to create via database
New Evaluation Criterion:
- Update
evaluation_checklist.json - Update evaluation prompt
- Update frontend evaluation display
New API Endpoint:
- Add to appropriate router in
backend/routers/ - Add service method if needed
- Update frontend
lib/api.ts - Add TypeScript interfaces
- Pre-clinical psychiatric training
- OSCE (Objective Structured Clinical Examination) preparation
- Therapeutic communication skills
- Risk assessment practice
- Interview technique refinement
- Cultural competency training
- Crisis assessment skills
- Diagnostic interviewing
- Mental health assessment
- Patient communication
- Empathy development
- Documentation skills
- Skills refresh for practitioners
- New assessment technique training
- Exposure to rare conditions
- Telehealth interview practice
- Switch to GPT-4o-mini (cost optimization)
- Add conversation history database
- Build transcript viewer UI
- Authentication guards on all pages
- User-friendly error messages
- Student progress dashboard
- Evaluator analytics dashboard
- Pagination for conversation lists
- Advanced filtering and search
- Email notifications
- Voice interface (speech-to-text, text-to-speech)
- Multi-language support
- Mobile app
- LMS integration (Canvas, Moodle)
- PDF export for evaluations
- Graph database for case knowledge (Neo4j)
- Full ERRG pipeline implementation
- Ensemble evaluation (multiple AI judges)
- Longitudinal progress tracking
- Predictive analytics
MIT License - See LICENSE file for details
- CureFun Paper: Li et al., 2024 - Research methodology foundation
- LangChain: Framework for LLM chains and memory
- OpenAI: GPT-4o-mini for cost-effective AI conversations
- FastAPI: Modern Python web framework
- Next.js: React framework for production-ready apps
For issues, questions, or contributions:
- Issues: Open a GitHub issue
- Documentation: Check SETUP_GUIDE.md, DATABASE_SETUP.md
- API Docs: http://localhost:8000/docs
# Backend
cd backend
source venv/bin/activate
uvicorn backend.main:app --reload --port 8000
alembic upgrade head
python -m scripts.create_admin
# Frontend
cd frontend
npm install
npm run dev
npm run build
# Docker
docker-compose up --build
docker-compose down
# Database
psql vsp_dummy
alembic current
alembic upgrade headBuilt with β€οΈ for mental health education