An enterprise-grade AI-powered patient risk assessment system that analyzes comprehensive patient data to predict risk levels and enable proactive healthcare delivery.
- Real-time Risk Scoring: 0-100 scale risk assessment with confidence intervals
- ML Ensemble: XGBoost, Random Forest, and Neural Network models for robust predictions
- Multi-source Integration: FHIR R4, EHR systems, medical devices, and manual entry
- Critical Patient Detection: Automated flagging and alerting for high-risk patients (β₯80 score)
- Contributing Factors Analysis: Detailed breakdown of risk factors influencing scores
- HIPAA Compliant: Comprehensive audit logging and data protection
- JWT Authentication: Role-based access control (Doctor, Nurse, Admin)
- Data Anonymization: Automatic PII removal for model training
- Audit Trails: Complete tracking of all data access and risk assessments
- Real-time Performance Metrics: Model accuracy, response times, system health
- Automated Model Retraining: Triggers when accuracy drops below 80%
- Health Monitoring: Component-level health checks and system diagnostics
- Batch Processing: Handle up to 100 patients per API call
- Property-Based Testing: Comprehensive test coverage using Hypothesis
- Integration Testing: End-to-end workflow validation
- API Documentation: Interactive Swagger/OpenAPI docs
- Type Safety: Full TypeScript-style type hints throughout
graph TB
A[Data Ingestion Layer] --> B[Data Validation & Preprocessing]
B --> C[Feature Engineering Pipeline]
C --> D[ML Model Ensemble]
D --> E[Risk Score Calculator]
E --> F[Alert Generation System]
F --> G[API Gateway]
G --> H[External Systems]
I[Model Training Pipeline] --> D
J[Model Performance Monitor] --> I
K[Data Storage Layer] --> B
K --> I
| Component | Description | Technology |
|---|---|---|
| Data Ingestion | Multi-source patient data processing | FHIR R4, HL7 v2.x |
| ML Ensemble | Risk prediction models | XGBoost, Random Forest, MLP |
| API Gateway | RESTful API with authentication | FastAPI, JWT |
| Alert System | Critical patient notifications | Real-time alerting |
| Audit System | Compliance and logging | Structured logging |
| Performance Monitor | System metrics and health | Custom metrics tracking |
carefluxa-ai/
βββ π src/ # Source code
β βββ π config.py # Configuration management
β βββ π logging_config.py # Logging setup
β βββ π startup.py # Application initialization
β βββ π integration.py # System integration layer
β βββ π data/ # Data processing & ingestion
β β βββ π models.py # Pydantic data models
β β βββ π ingestion.py # Multi-source data ingestion
β β βββ π integration.py # Data source integration
β β βββ π validation.py # Data validation rules
β βββ π api/ # REST API & web interface
β β βββ π app.py # FastAPI application
β β βββ π auth.py # Authentication & authorization
β β βββ π models.py # API request/response models
β β βββ π risk_service.py # Risk assessment service
β βββ π alerts/ # Alert generation system
β β βββ π alert_system.py # Alert management
β β βββ π critical_detection.py # Critical patient detection
β βββ π audit/ # Audit logging & compliance
β β βββ π logger.py # Audit trail generation
β β βββ π compliance.py # HIPAA compliance tools
β β βββ π models.py # Audit data models
β βββ π performance/ # Performance monitoring
β β βββ π performance_monitor.py # System performance tracking
β β βββ π metrics_tracker.py # Metrics collection
β β βββ π models.py # Performance data models
β βββ π privacy/ # Data privacy & anonymization
β βββ π anonymization.py # PII removal for training
β βββ π validation.py # Privacy compliance checks
βββ π tests/ # Comprehensive test suite
β βββ π unit/ # Unit tests
β βββ π integration/ # Integration tests
β βββ π property/ # Property-based tests (Hypothesis)
βββ π docs/ # Documentation and specifications
β βββ π specs/ # Feature specifications
βββ π main.py # Application entry point
βββ π requirements.txt # Python dependencies
βββ π pyproject.toml # Project configuration
βββ π Makefile # Development commands
βββ π README.md # This file
- Python 3.9+ (3.12 recommended)
- pip or poetry for dependency management
- Git for version control
- Clone the repository:
git clone https://github.com/adenueltech/carefluxa-ai.git
cd carefluxa-ai- Create virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies:
pip install -r requirements.txt- Set up environment variables:
cp .env.example .env
# Edit .env with your configuration
export DATABASE_URL="sqlite:///./carefluxa.db"
export SECRET_KEY="your-secret-key-here"Start the server:
python main.pyAccess the application:
- π Main API: http://localhost:8000
- π Interactive Docs: http://localhost:8000/docs
- π ReDoc Documentation: http://localhost:8000/redoc
- β€οΈ Health Check: http://localhost:8000/health
Run all tests:
pytestRun with coverage:
pytest --cov=src --cov-report=htmlRun specific test types:
# Unit tests only
pytest tests/unit/
# Integration tests only
pytest tests/integration/
# Property-based tests only
pytest tests/property/Using the Makefile:
make install # Install dependencies
make test # Run tests
make lint # Code linting
make format # Code formatting
make clean # Clean up temporary files# Login to get JWT token
curl -X POST "http://localhost:8000/api/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{"username": "doctor_smith", "password": "secure_password"}'
# Response
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"token_type": "bearer",
"expires_in": 3600,
"user_id": "doc_001",
"role": "doctor"
}# Assess individual patient risk
curl -X POST "http://localhost:8000/api/v1/risk-assessment" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"patient_id": "patient_12345",
"include_factors": true,
"force_refresh": true
}'
# Response
{
"success": true,
"patient_id": "patient_12345",
"risk_assessment": {
"risk_score": 85,
"confidence_interval": [78, 92],
"alert_level": "critical",
"contributing_factors": [
{
"factor_name": "Elevated Heart Rate",
"impact_score": 15.2,
"category": "vitals"
},
{
"factor_name": "Diabetes History",
"impact_score": 12.8,
"category": "medical_history"
}
],
"assessment_timestamp": "2024-01-12T10:30:00Z"
},
"processing_time_ms": 245.7
}# Get current critical patients
curl -X GET "http://localhost:8000/api/v1/critical-patients" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
# Response
{
"critical_patients": [
{
"patient_id": "patient_12345",
"risk_score": 85,
"alert_level": "critical",
"last_assessment": "2024-01-12T10:30:00Z",
"time_in_critical_status": "02:15:30"
}
],
"total_count": 1,
"last_updated": "2024-01-12T10:30:00Z"
}# Get performance metrics (Admin only)
curl -X GET "http://localhost:8000/api/v1/performance-metrics" \
-H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN"
# Response
{
"individual_models": [
{
"model_name": "XGBoost",
"accuracy": 0.92,
"precision": 0.89,
"recall": 0.94,
"f1_score": 0.91,
"auc_roc": 0.95
}
],
"ensemble_accuracy": 0.94,
"average_response_time_ms": 850.0,
"assessments_per_hour": 450.0,
"critical_alerts_generated": 12,
"system_uptime_percent": 99.8
}Create a .env file with the following configuration:
# Database Configuration
DATABASE_URL=sqlite:///./carefluxa.db
DATABASE_TEST_URL=sqlite:///./test_carefluxa.db
# API Configuration
API_HOST=0.0.0.0
API_PORT=8000
API_RELOAD=true
# Security
SECRET_KEY=your-super-secret-key-change-this-in-production
ACCESS_TOKEN_EXPIRE_MINUTES=60
# ML Model Configuration
CRITICAL_RISK_THRESHOLD=80
BATCH_SIZE_LIMIT=100
MODEL_RETRAIN_THRESHOLD=0.80
# Logging
LOG_LEVEL=INFO
ENABLE_METRICS=true
# Environment
ENVIRONMENT=development # development, testing, production| Category | Description | Environment Variables |
|---|---|---|
| Database | SQLite/PostgreSQL connection | DATABASE_URL, DATABASE_TEST_URL |
| API | Server settings and CORS | API_HOST, API_PORT, API_RELOAD |
| Security | JWT tokens and encryption | SECRET_KEY, ACCESS_TOKEN_EXPIRE_MINUTES |
| ML Models | Risk thresholds and limits | CRITICAL_RISK_THRESHOLD, BATCH_SIZE_LIMIT |
| Monitoring | Logging and metrics | LOG_LEVEL, ENABLE_METRICS |
| Test Type | Coverage | Description |
|---|---|---|
| Unit Tests | 85% | Individual component testing |
| Integration Tests | 90% | End-to-end workflow validation |
| Property Tests | 95% | Hypothesis-based correctness validation |
| API Tests | 100% | Complete API endpoint coverage |
We use Hypothesis for property-based testing to ensure correctness across all possible inputs:
# Example: Risk score validity property
@given(patient_data=patient_data_strategy())
def test_risk_score_always_valid_range(patient_data):
"""Risk scores must always be between 0-100."""
response = risk_service.assess_patient_risk(patient_data)
assert 0 <= response.risk_assessment.risk_score <= 100# Run property-based tests with verbose output
pytest tests/property/ -v --hypothesis-show-statistics
# Run integration tests for specific component
pytest tests/integration/test_system_integration.py -v
# Run tests with coverage report
pytest --cov=src --cov-report=term-missingOnce the application is running, explore the comprehensive API documentation:
- Swagger UI: http://localhost:8000/docs - Interactive API testing
- ReDoc: http://localhost:8000/redoc - Beautiful API documentation
- OpenAPI Schema: http://localhost:8000/openapi.json - Machine-readable API spec
| Endpoint | Method | Description | Auth Required |
|---|---|---|---|
/health |
GET | System health check | β |
/api/v1/auth/login |
POST | User authentication | β |
/api/v1/risk-assessment |
POST | Individual patient risk assessment | β |
/api/v1/risk-assessment/batch |
POST | Batch patient risk assessment | β |
/api/v1/critical-patients |
GET | Get critical patients list | β |
/api/v1/performance-metrics |
GET | System performance metrics | β (Admin) |
/api/v1/ingest/patient |
POST | Ingest complete patient data | β |
/api/v1/ingest/fhir-bundle |
POST | Ingest FHIR R4 bundle | β |
The system uses JWT-based authentication with role-based access control:
- Doctor: Can assess patients, view critical patients
- Nurse: Can assess patients, manage alerts
- Admin: Full system access including performance metrics
We maintain high code quality through:
- Type Hints: Full type annotation coverage
- Linting: Flake8 for code style enforcement
- Formatting: Black for consistent code formatting
- Testing: 95%+ test coverage requirement
- Documentation: Comprehensive docstrings and API docs
# 1. Create feature branch
git checkout -b feature/new-feature
# 2. Make changes and test
make test
make lint
make format
# 3. Run full test suite
pytest --cov=src
# 4. Commit and push
git add .
git commit -m "feat: add new feature"
git push origin feature/new-feature- Update Requirements: Add to
docs/specs/if it's a major feature - Write Tests First: Follow TDD approach
- Implement Feature: Keep functions small and focused
- Add Documentation: Update API docs and README
- Test Integration: Ensure end-to-end workflows work
# 1. Set production environment
export ENVIRONMENT=production
export DATABASE_URL=postgresql://user:pass@host:5432/carefluxa
export SECRET_KEY=your-production-secret-key
# 2. Install production dependencies
pip install -r requirements.txt
# 3. Run database migrations (if applicable)
# python -m alembic upgrade head
# 4. Start with production server
uvicorn src.api.app:app --host 0.0.0.0 --port 8000 --workers 4# Dockerfile example
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY src/ ./src/
COPY main.py .
EXPOSE 8000
CMD ["python", "main.py"]We welcome contributions! Please follow these guidelines:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Follow code standards: Use Black formatting and type hints
- Add tests: Maintain 95%+ coverage
- Update documentation: Keep README and API docs current
- Submit a Pull Request
- Python Style: Follow PEP 8 with Black formatting
- Type Hints: All functions must have type annotations
- Docstrings: Use Google-style docstrings
- Testing: Write both unit and property-based tests
- Commit Messages: Use conventional commits (feat:, fix:, docs:)
# Install development dependencies
pip install -e ".[dev]"
# Set up pre-commit hooks
pre-commit install
# Run quality checks
make lint
make format
make testThis project is licensed under the MIT License - see the LICENSE file for details.
- FastAPI - Modern, fast web framework for building APIs
- Hypothesis - Property-based testing framework
- Pydantic - Data validation using Python type annotations
- XGBoost - Gradient boosting framework for ML
- FHIR - Healthcare interoperability standards
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: API Docs
Built with β€οΈ for better healthcare outcomes