Skip to content

Latest commit

Β 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Dual-Interface AI Health Platform: Web Chatbot + SMS for Emergency Triage & Appointments

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.

🎭 Who Is This For?

  • 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

✨ Key Features

πŸ€– AI-Powered Health Triage

  • Natural language understanding for medical queries
  • Context-aware responses using OpenAI GPT models
  • Multi-turn conversation support with session management

🚨 Emergency Escalation System

  • Automatic detection of emergency keywords
  • Instant human operator alerts for critical situations
  • Customizable escalation rules and triggers

πŸ“… Smart Appointment Booking

  • Conversational appointment scheduling
  • Multi-step booking workflow (purpose β†’ patient β†’ date β†’ time β†’ specialist)
  • Automated confirmation and reminder system

🏒 Multi-Organization Support

  • Customizable prompts per organization type (SMB, Provider, Platform)
  • Organization-specific routing and responses
  • White-label ready architecture

πŸ“Š Comprehensive Logging

  • In-memory webhook event logging
  • Session tracking and conversation history
  • API call monitoring and debugging tools

πŸ—οΈ System Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                           β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   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)β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ”§ Tech Stack

  • 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

πŸš€ Quick Start

Prerequisites

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

⚑ One-Command Setup

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

πŸ“¦ Installation

Option 1: Docker Deployment (Recommended)

  1. Clone the repository

    git clone https://github.com/your-org/twilio-ai-health-triage.git
    cd twilio-ai-health-triage
  2. Set up environment variables

    cp .env.example .env
    nano .env  # Edit with your credentials
  3. Build and run

    docker compose up --build -d

Option 2: Local Development

  1. Install Python dependencies

    pip install -r requirements.txt
  2. Run the FastAPI application

    uvicorn com.mhire.app.main:app --reload --host 0.0.0.0 --port 8000

βš™οΈ Configuration

Environment Variables

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=INFO

Organization Types

The 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

πŸ“– API Documentation

Core Endpoints

πŸ’¬ Web Chat API

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
}

πŸ“± SMS Webhook (Twilio)

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=SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

πŸ“Š Webhook Logs

GET /api/v1/webhooks/visit-logged?limit=50

Interactive API Documentation

Once running, visit:

  • Swagger UI: http://localhost:5020/docs
  • ReDoc: http://localhost:5020/redoc

πŸš€ Deployment

Production Deployment with Docker

  1. Prepare production environment

    # Set production environment variables
    export ENVIRONMENT=production
    export DEBUG=false
  2. Deploy with Docker Compose

    docker compose -f docker-compose.prod.yml up -d
  3. Configure Twilio Webhook URL

    • Set your Twilio webhook URL to: https://yourdomain.com/api/v1/chat/send
    • Ensure HTTP POST method is selected

Scaling Considerations

  • 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

πŸ’‘ Usage Examples

πŸ’‘ Usage Examples

Web Chat Interface

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."

SMS Interface (Mobile Phone)

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."

General Health Query

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?

🏒 Project Structure

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

🀝 Contributing

We welcome contributions! Here's how to get started:

Development Setup

  1. Fork and clone the repository

    git clone https://github.com/your-username/twilio-ai-health-triage.git
    cd twilio-ai-health-triage
  2. Create a virtual environment

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies

    pip install -r requirements.txt
    pip install -r requirements-dev.txt  # Development dependencies
  4. Run tests

    pytest tests/

Contribution Guidelines

  • πŸ› 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

Pull Request Process

  1. Create a feature branch: git checkout -b feature/your-feature-name
  2. Make your changes with tests
  3. Run the test suite: pytest
  4. Update documentation if needed
  5. Submit a pull request with a clear description

πŸ”’ Security & Privacy

Data Handling

  • 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

Emergency Protocols

  • 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

πŸ“Š Monitoring & Analytics

Built-in Logging

  • Webhook Events: All Twilio interactions logged
  • AI Conversations: Chat sessions tracked with metadata
  • Error Tracking: Comprehensive error logging and handling

Integration Ready

  • Prometheus Metrics: Add /metrics endpoint for monitoring
  • Health Checks: Built-in health check endpoints
  • Performance Monitoring: Request timing and response metrics

πŸ†˜ Troubleshooting

Common Issues

Twilio Webhook Not Receiving Messages

# 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"

OpenAI API Errors

# Verify API key
export OPENAI_API_KEY=your_key_here
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
  https://api.openai.com/v1/models

Docker Build Issues

# Clean build
docker compose down
docker system prune -f
docker compose up --build --force-recreate

πŸ“œ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgements

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

About

Dual-Interface AI Health Platform: Web Chatbot + SMS for Emergency Triage & Appointments

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages