Twilio AI Health Triage is a comprehensive dual-interface healthcare platform that provides both web-based chatbot and SMS communication channels. Tech-savvy users can interact through a modern web interface (currently fastapi chatbot endpoint), while non-technical users can simply communication with AI from their mobile phones via sms. The system combines AI-powered chatbot capabilities with intelligent triage and emergency escalation, seamlessly handling patient inquiries across both channels.
- Tech-Savvy Patients - Web interface with instant chat responses
- Non-Technical Users - Simple SMS texting from any mobile phone
- Healthcare Providers - Streamline patient communication across all channels
- Medical SMBs - Automate appointment booking and basic health queries
- Platform Companies - Integrate health triage into existing systems
- Natural language understanding for medical queries
- Context-aware responses using OpenAI GPT models
- Multi-turn conversation support with session management
- Automatic detection of emergency keywords
- Instant human operator alerts for critical situations
- Customizable escalation rules and triggers
- Conversational appointment scheduling
- Multi-step booking workflow (purpose β patient β date β time β specialist)
- Automated confirmation and reminder system
- Customizable prompts per organization type (SMB, Provider, Platform)
- Organization-specific routing and responses
- White-label ready architecture
- In-memory webhook event logging
- Session tracking and conversation history
- API call monitoring and debugging tools
βββββββββββββββββββ βββββββββββββββββββββββ
β Chat API β-------------------------->β β
β /api/v1/chat β β β
βββββββββββββββββββ β β
β FastAPI Backend β
βββββββββββββββββββ βββββββββββββββββββ β (Core Engine) β
β Patient SMS β--->β Twilio Webhook β--->β β
β (Mobile Phone) β β/api/v1/chat/sendβ β β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββββββ
β
βββββββββββββββββββ β
β Session Manager β<--------------β
β β β
β (Memory/Redis) β β
βββββββββββββββββββ β
β
βββββββββββββββββββ β
β OpenAI API β<--------------β
β (GPT-3.5/4 AI) β β
βββββββββββββββββββ β
β
βββββββββββββββββββ βββββββββββββββββββ β
β Human Escalationβ<---β Triage Engine β β
β (Emergency Ops) β β (Keyword Detect)β<--------------β
βββββββββββββββββββ βββββββββββββββββββ β
β
βββββββββββββββββββ βββββββββββββββββββ β
β Appointment Sys β<---β Booking Engine β<--------------β
β (Calendar/EHR) β β(Multi-step Flow)β
βββββββββββββββββββ βββββββββββββββββββ
- Backend: FastAPI (Python 3.10+)
- AI Engine: OpenAI GPT-3.5/4 with LangChain
- SMS Gateway: Twilio SMS API
- Session Management: In-memory storage (Redis ready)
- Containerization: Docker & Docker Compose
- Reverse Proxy: Nginx
Before you begin, ensure you have:
- Python 3.10+ installed
- Docker & Docker Compose for containerized deployment
- Twilio Account with SMS capabilities
- OpenAI API Key for AI functionality
git clone https://github.com/syeda434am/Twilio-AI-Health-Triage.git
cd Twilio-AI-Health-Triage
cp .env
# Edit .env with your credentials
docker compose up --buildπ That's it! Your dual-interface health triage system is now running at:
- Web Chat Interface:
http://localhost:5020 - SMS Webhook Endpoint:
http://localhost:5020/api/v1/chat/send
-
Clone the repository
git clone https://github.com/your-org/twilio-ai-health-triage.git cd twilio-ai-health-triage -
Set up environment variables
cp .env.example .env nano .env # Edit with your credentials -
Build and run
docker compose up --build -d
-
Install Python dependencies
pip install -r requirements.txt
-
Run the FastAPI application
uvicorn com.mhire.app.main:app --reload --host 0.0.0.0 --port 8000
Create a .env file in the project root:
# OpenAI Configuration
OPENAI_API_KEY=sk-your-openai-api-key-here
OPENAI_MODEL=gpt-3.5-turbo
# Twilio Configuration
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_twilio_auth_token_here
TWILIO_PHONE_NUMBER=+1234567890
# Organization Lookup
PHONE_LOOKUP_ENDPOINT=https://api.yourorg.com/lookup
# Application Settings
DEBUG=false
LOG_LEVEL=INFOThe system supports three organization types with customized prompts:
| Type | Description | Use Case |
|---|---|---|
| SMB | Small Medical Business | Clinics, private practices |
| PROVIDER | Healthcare Provider | Hospitals, medical centers |
| PLATFORM | Platform Company | Health tech platforms |
POST /api/v1/chat
Content-Type: application/json
{
"message": "I have chest pain and difficulty breathing",
"organization_type": "PROVIDER",
"session_id": "web_user_12345"
}Response:
{
"response": "This sounds like a medical emergency. I'm connecting you with a healthcare professional immediately.",
"escalation_type": "EMERGENCY",
"session_id": "web_user_12345",
"requires_human": true
}POST /api/v1/chat/send
Content-Type: application/x-www-form-urlencoded
Body=Hello, I need to book an appointment
From=+1234567890
To=+0987654321
MessageSid=SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxGET /api/v1/webhooks/visit-logged?limit=50Once running, visit:
- Swagger UI:
http://localhost:5020/docs - ReDoc:
http://localhost:5020/redoc
-
Prepare production environment
# Set production environment variables export ENVIRONMENT=production export DEBUG=false
-
Deploy with Docker Compose
docker compose -f docker-compose.prod.yml up -d
-
Configure Twilio Webhook URL
- Set your Twilio webhook URL to:
https://yourdomain.com/api/v1/chat/send - Ensure HTTP POST method is selected
- Set your Twilio webhook URL to:
- Redis Integration: Replace in-memory sessions with Redis for horizontal scaling
- Database: Add PostgreSQL for persistent conversation history
- Load Balancer: Use multiple FastAPI instances behind a load balancer
- Message Queue: Implement Celery for background task processing
Emergency via Web:
User types in web chat: "Help! I'm having severe chest pain and can't breathe properly!"
System Response (displayed in chat):
π¨ EMERGENCY DETECTED π¨
This sounds like a medical emergency. I'm immediately
connecting you with emergency medical services.
Stay calm and call 911 if you haven't already.
A healthcare professional will contact you shortly.
Reference ID: EMRG_20241226_001
Appointment Booking via Web:
User: "I need to book an appointment"
Bot: "I'll help you schedule an appointment. What's the purpose of your visit?"
User: "Annual checkup"
Bot: "Great! What's the patient's name?"
User: "John Smith"
Bot: "Thank you. What date works best for you?"
User: "Next Tuesday"
Bot: "Perfect! What time would you prefer? (Morning/Afternoon/Evening)"
User: "Morning"
Bot: "Excellent! Your appointment is scheduled:
π
Date: Tuesday, Jan 2nd, 2024
β° Time: 9:00 AM
π€ Patient: John Smith
π Purpose: Annual checkup
You'll receive a confirmation message shortly."
Emergency via SMS:
π± Patient texts: "Help chest pain bad"
π² System responds: "π¨ EMERGENCY - This sounds serious.
Emergency services contacted. Call 911 now if you haven't.
Stay calm. Help is coming. Ref: EMRG_001"
Appointment via SMS:
π± "book appointment"
π² "I'll help you schedule. What's the visit for?"
π± "checkup"
π² "Great! Patient name?"
π± "John Smith"
π² "Thanks! Preferred date?"
π± "next tuesday"
π² "Time preference? Reply: 1-Morning, 2-Afternoon, 3-Evening"
π± "1"
π² "β
Booked! Tue Jan 2, 9AM for John Smith (checkup).
Confirmation coming via SMS."
Patient Input:
"What should I do about a persistent headache?"
System Response:
For persistent headaches, here are some general recommendations:
π Immediate relief:
- Stay hydrated
- Rest in a quiet, dark room
- Consider over-the-counter pain relievers
β οΈ See a doctor if you experience:
- Sudden, severe headaches
- Headaches with fever or neck stiffness
- Vision changes or confusion
Would you like to schedule an appointment for evaluation?
twilio-ai-health-triage/
βββ π com/mhire/app/
β βββ π main.py # FastAPI application entry point
β βββ π config/ # Configuration management
β βββ π common/ # Shared utilities and responses
β βββ π services/
β βββ π chatbot_services/ # AI chatbot logic
β β βββ π€ ai_chatbot.py # Core AI functionality
β β βββ π session_manager.py # Session tracking
β β βββ π
appointment_booking.py # Booking workflows
β β βββ π¨ escalation_dictionary.py # Emergency keywords
β β βββ π¬ prompt_dictionary.py # AI prompts
β βββ π twilio_services/ # Twilio integration
β βββ π± twilio_inbound.py # SMS webhook handling
β βββ π webhook_log_manager.py # Logging system
βββ π nginx/
β βββ βοΈ nginx.conf # Reverse proxy configuration
βββ π³ Dockerfile # Container definition
βββ π compose.yaml # Docker Compose setup
βββ π requirements.txt # Python dependencies
βββ π§ .env.example # Environment template
βββ π README.md # This file
We welcome contributions! Here's how to get started:
-
Fork and clone the repository
git clone https://github.com/your-username/twilio-ai-health-triage.git cd twilio-ai-health-triage -
Create a virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt pip install -r requirements-dev.txt # Development dependencies -
Run tests
pytest tests/
- π Bug Reports: Use GitHub Issues with detailed reproduction steps
- β¨ Feature Requests: Propose new features with use cases and examples
- π§ Code Style: Follow PEP 8 and use Black for formatting
- β Testing: Add tests for new features and bug fixes
- π Documentation: Update README and docstrings for changes
- Create a feature branch:
git checkout -b feature/your-feature-name - Make your changes with tests
- Run the test suite:
pytest - Update documentation if needed
- Submit a pull request with a clear description
- No Persistent Storage: Conversations are stored in-memory only
- Session Security: Session IDs are generated securely
- API Key Protection: Environment variables for sensitive data
- HIPAA Considerations: Designed with healthcare privacy in mind
- Immediate Escalation: Critical keywords trigger instant human alerts
- Audit Trail: All emergency escalations are logged with timestamps
- Failsafe Mechanisms: System defaults to human escalation on uncertainty
- Webhook Events: All Twilio interactions logged
- AI Conversations: Chat sessions tracked with metadata
- Error Tracking: Comprehensive error logging and handling
- Prometheus Metrics: Add
/metricsendpoint for monitoring - Health Checks: Built-in health check endpoints
- Performance Monitoring: Request timing and response metrics
# Check webhook URL configuration
curl -X POST http://localhost:5020/api/v1/chat/send \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "Body=test&From=+1234567890&To=+0987654321"# Verify API key
export OPENAI_API_KEY=your_key_here
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
https://api.openai.com/v1/models# Clean build
docker compose down
docker system prune -f
docker compose up --build --force-recreateThis project is licensed under the MIT License - see the LICENSE file for details.
Special thanks to the amazing technologies and communities that make this project possible:
- Twilio - Reliable SMS infrastructure
- OpenAI - Powerful AI language models
- FastAPI - Modern, fast web framework
- LangChain - AI application development framework
- Docker - Containerization platform