Skip to content

VaidhyaMegha/samyama-trial-enrollment-agent

Repository files navigation

Samyama's Clinical Trial Enrollment Agent - Backend

Samyama Clinical Trial Enrollment Bedrock Mistral Large 2 Python License

AI-Powered Clinical Trial Patient Matching with Amazon Bedrock (Mistral Large 2)

Live Demo β€’ Frontend Repo β€’ AWS Hackathon


πŸ“‘ Table of Contents


🎯 Overview

Samyama's Clinical Trial Enrollment Agent is an autonomous AI agent that revolutionizes clinical trial enrollment by automating patient-trial matching. Built for the AWS AI Agent Global Hackathon 2025, this system reduces enrollment time from weeks to minutes using intelligent automation powered by Amazon Bedrock with Mistral Large 2.

The Problem

85% of clinical trials fail due to slow patient enrollment. Traditional manual screening is:

  • Time-consuming (weeks of coordinator effort)
  • Error-prone (manual criteria interpretation)
  • Expensive (millions in delayed drug development)
  • Inconsistent (subjective eligibility decisions)

Our Solution

An intelligent AI agent that:

  • πŸ“„ Parses clinical trial protocols using AWS Textract and Mistral Large 2
  • πŸ” Analyzes patient health records from AWS HealthLake (FHIR R4)
  • 🧠 Matches patients to trials with explainable AI reasoning
  • πŸ“Š Generates confidence-scored eligibility reports

πŸ—οΈ Architecture

Architecture Diagram

6-Layer Architecture

  1. User Personas Layer: CRC, StudyAdmin, PI with role-based access
  2. Frontend Layer: CloudFront CDN β†’ S3 β†’ React Application
  3. Authentication & API Layer: Cognito (3 user groups) β†’ API Gateway β†’ Lambda Authorizer
  4. AI Agent Layer: 10 Lambda functions orchestrating the AI pipeline
  5. AI Services Layer: Bedrock (Mistral Large 2), Textract, Comprehend Medical, HealthLake
  6. Data Persistence Layer: 3 DynamoDB tables, S3, CloudWatch

✨ Key Features

πŸ€– Autonomous AI Agent Pipeline

Protocol Processing Pipeline

6-Phase Automated Protocol Processing:

  1. Document Upload - Secure upload to S3
  2. Text Extraction - AWS Textract OCR from PDF
  3. Medical Analysis - AWS Comprehend Medical entity extraction
  4. Criteria Classification - Organize inclusion/exclusion criteria
  5. Data Structuring - Amazon Bedrock (Mistral Large 2) parsing
  6. Finalization - Save to DynamoDB cache

🎯 Intelligent Eligibility Matching

Eligibility Results

AI-Powered Patient Matching with:

  • Mistral Large 2 reasoning for complex medical criteria
  • Confidence scores (0-100%) for each criterion
  • Criterion-by-criterion explanations with evidence
  • FHIR resource integration (11 resource types)
  • Transparent decision-making with audit trails

πŸ“Š Three User Personas

Clinical Research Coordinator (CRC)

CRC Dashboard

  • Patient screening and eligibility checking
  • View match confidence scores
  • Track success rates (78% in demo)

Study Administrator (StudyAdmin)

StudyAdmin Dashboard

  • Protocol upload and management
  • Monitor processing pipeline
  • Track protocol status distribution

Principal Investigator (PI)

PI Dashboard

  • Enrollment oversight across trials
  • Review pending matches
  • Approve/reject enrollments
  • Export professional reports

πŸ› οΈ Technology Stack

AWS Services (11 Total)

Service Purpose Usage
Amazon Bedrock LLM Reasoning Mistral Large 2 (mistral.mistral-large-2402-v1:0) for criteria parsing and eligibility decisions
AWS Lambda Serverless Compute 10 functions for agent execution
AWS HealthLake FHIR R4 Datastore Patient health records (11 resource types)
AWS Textract Document OCR Extract text from protocol PDFs
Amazon Comprehend Medical Medical NLP Entity extraction and NER
Amazon DynamoDB NoSQL Database 3 tables: criteria cache, evaluation results, matches
Amazon Cognito Authentication User pools with 3 groups (CRC, StudyAdmin, PI)
Amazon API Gateway REST API API endpoints for frontend integration
Amazon S3 Object Storage Protocol documents and static website hosting
Amazon CloudFront CDN Global content delivery
Amazon CloudWatch Observability Logging, monitoring, tracing

Additional Technologies

  • Infrastructure as Code: AWS CDK (Python)
  • Backend: Python 3.11+ with AWS Lambda Powertools
  • Frontend: React + TypeScript + Tailwind CSS
  • FHIR Compliance: FHIR R4 standard (11 resource types)
  • Testing: pytest with 93% pass rate

πŸ“‹ FHIR Resource Support

Supports 11 FHIR R4 resource types for comprehensive patient data:

  1. Patient - Demographics, birthDate, gender
  2. Condition - Diagnoses, ICD-10 codes
  3. Observation - Lab values, vital signs
  4. MedicationStatement - Current medications
  5. AllergyIntolerance - Allergies and intolerances
  6. Procedure - Surgical history
  7. Immunization - Vaccination records
  8. DiagnosticReport - Lab reports
  9. Encounter - Healthcare visits
  10. CarePlan - Treatment plans
  11. FamilyMemberHistory - Family medical history

πŸš€ Quick Start

Prerequisites

  • AWS Account with:
    • Amazon Bedrock access (Mistral Large 2 enabled in us-east-1)
    • HealthLake permissions
    • Lambda, API Gateway, and DynamoDB permissions
  • Python 3.11+
  • AWS CLI configured
  • Node.js 18+ (for AWS CDK)

Installation

# 1. Clone the repository
git clone https://github.com/VaidhyaMegha/samyama-trial-enrollment-agent.git
cd samyama-trial-enrollment-agent

# 2. Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# 3. Install dependencies
pip install -r requirements.txt

# 4. Configure AWS credentials
aws configure
# Set region to us-east-1 for Bedrock access

# 5. Deploy infrastructure
cd infrastructure
npm install -g aws-cdk
pip install -r requirements.txt
cdk deploy --require-approval never

# 6. Load synthetic patient data
cd ../scripts
python3 upload_to_healthlake.py

Enable Bedrock Model Access

  1. Go to AWS Console β†’ Bedrock β†’ Model access
  2. Enable Mistral Large 2 (mistral.mistral-large-2402-v1:0)
  3. Wait for approval (usually instant)

πŸ“¦ Project Structure

samyama-trial-enrollment-agent/
β”œβ”€β”€ docs/                             # Documentation
β”‚   β”œβ”€β”€ PROTOCOL_PROCESSING_GUIDE.md  # Protocol processing guide
β”‚   β”œβ”€β”€ screenshots/                  # 15 demo screenshots
β”‚   └── AWS Hackathon Idea _ v1.md    # Original concept
β”œβ”€β”€ src/                              # Source code
β”‚   β”œβ”€β”€ lambda/                       # Lambda functions
β”‚   β”‚   β”œβ”€β”€ criteria_parser/          # Mistral Large 2 parsing (core AI)
β”‚   β”‚   β”œβ”€β”€ fhir_search/              # HealthLake FHIR queries
β”‚   β”‚   β”œβ”€β”€ textract_processor/       # PDF text extraction
β”‚   β”‚   β”œβ”€β”€ section_classifier/       # Comprehend Medical classification
β”‚   β”‚   β”œβ”€β”€ protocol_orchestrator/    # Pipeline orchestration
β”‚   β”‚   β”œβ”€β”€ protocol_manager/         # Protocol CRUD operations
β”‚   β”‚   β”œβ”€β”€ patient_manager/          # Patient data management
β”‚   β”‚   β”œβ”€β”€ match_manager/            # Patient-protocol matching
β”‚   β”‚   β”œβ”€β”€ admin_manager/            # System administration
β”‚   β”‚   └── authorizer/               # JWT authentication
β”‚   β”œβ”€β”€ agent/                        # Agent configuration
β”‚   └── utils/                        # Shared utilities
β”œβ”€β”€ infrastructure/                   # AWS CDK Infrastructure
β”‚   └── app.py                        # CDK stack definition
β”œβ”€β”€ scripts/                          # Utility scripts
β”‚   β”œβ”€β”€ process_protocol_pdf.py       # End-to-end protocol processor
β”‚   β”œβ”€β”€ load_synthea_data.py          # Generate synthetic FHIR data
β”‚   β”œβ”€β”€ upload_to_healthlake.py       # Upload patients to HealthLake
β”‚   └── end_to_end_demo.py            # Complete workflow demo
β”œβ”€β”€ tests/                            # Test suites (pytest)
β”‚   β”œβ”€β”€ test_criteria_parser.py       # Criteria parser tests
β”‚   └── test_fhir_search.py           # FHIR search tests
β”œβ”€β”€ protocol-docs/                    # Sample protocol PDFs
β”œβ”€β”€ requirements.txt                  # Python dependencies
└── README.md                         # This file

πŸ§ͺ Testing

# Set environment variables
export POWERTOOLS_TRACE_DISABLED=1
export AWS_XRAY_CONTEXT_MISSING=LOG_ERROR

# Run all tests
pytest tests/ -v --tb=short

# Run with coverage
pytest tests/ --cov=src --cov-report=html

# Run end-to-end demo
python scripts/end_to_end_demo.py

Test Results: 14/15 tests passing (93% pass rate)


πŸ“Š API Endpoints

POST /parse-criteria

Parse eligibility criteria using Mistral Large 2.

Request:

{
  "criteria_text": "Patients must be between 18 and 65 years old",
  "trial_id": "trial-001"
}

Response:

{
  "criteria": [{
    "type": "inclusion",
    "category": "demographics",
    "description": "Age between 18 and 65 years",
    "attribute": "age",
    "operator": "between",
    "value": [18, 65],
    "unit": "years",
    "fhir_resource": "Patient",
    "fhir_path": "Patient.birthDate"
  }],
  "trial_id": "trial-001"
}

POST /check-criteria

Check patient eligibility with AI reasoning.

Request:

{
  "patient_id": "patient-001",
  "criteria": [...]
}

Response:

{
  "patient_id": "patient-001",
  "eligible": true,
  "confidence": 92,
  "results": [{
    "met": true,
    "confidence": 95,
    "reason": "Patient age is 46 years (within range 18-65)",
    "evidence": {
      "birthDate": "1979-05-15",
      "calculated_age": 46
    }
  }]
}

πŸŽ₯ Demo Video

Watch our 3-minute demo showcasing the complete workflow:

Watch Demo Video

Video Highlights:

  • All three user personas (CRC, StudyAdmin, PI)
  • Protocol upload and AI processing pipeline
  • Patient eligibility checking with Mistral Large 2 reasoning
  • Real-time match results with confidence scores
  • Complete end-to-end workflow demonstration

🌐 Live Deployment

Production URL: https://enrollment.samyama.care

Deployed Infrastructure (us-east-1):

  • API Gateway: https://gt7dlyqj78.execute-api.us-east-1.amazonaws.com/prod/
  • CloudFront Distribution: https://d25df0kqd06e10.cloudfront.net
  • HealthLake Datastore: 8640ed6b344b85e4729ac42df1c7d00e

⚠️ Demo Environment Notice

This is a demonstration deployment for the AWS AI Agent Hackathon 2025:

  • All patient data is synthetic (generated via Synthea - no real PHI)
  • Demo accounts are isolated with no production data access
  • Test credentials are for demonstration purposes only
  • For hackathon evaluation and testing only

To run your own instance, follow the Quick Start guide or contact project maintainers for setup assistance.


πŸ† AWS Hackathon Compliance

Required Technologies βœ…

  • Amazon Bedrock: Mistral Large 2 (mistral.mistral-large-2402-v1:0) for AI reasoning
  • AWS Lambda: 10 serverless functions for agent execution
  • Multiple AWS Services: DynamoDB, HealthLake, Textract, Comprehend Medical, Cognito, API Gateway, S3, CloudFront

Agent Qualification βœ…

a) Reasoning Capabilities:

  • Analyzes complex medical eligibility criteria
  • Makes intelligent decisions with confidence scores
  • Provides explainable AI reasoning
  • Handles edge cases and ambiguous criteria

b) Autonomous Execution:

  • Automatically processes protocol PDF uploads via S3 triggers
  • Self-initiates eligibility evaluations through orchestration
  • Manages state across multi-step workflows
  • Error handling and recovery without human intervention

c) External Integration:

  • AWS HealthLake FHIR API (11 resource types)
  • Amazon Bedrock API (Mistral Large 2)
  • AWS Textract API (document processing)
  • Amazon Comprehend Medical API (medical NER)
  • DynamoDB for state management

πŸ“ˆ Impact & Value

Real-World Benefits

  • ⏱️ Time Savings: Reduces enrollment screening from weeks to minutes
  • πŸ’° Cost Reduction: Saves millions in trial delays
  • 🎯 Improved Accuracy: AI-powered consistent eligibility decisions
  • πŸ“Š Better Insights: Confidence scores and explainable reasoning
  • πŸ”’ HIPAA-Eligible: All AWS services are HIPAA-eligible
  • 🌍 Scalable: Serverless architecture for global deployment

Metrics

  • 247 patients screened (demo data)
  • 78% success rate
  • 92% average confidence score for matches
  • <90 seconds to process 26-page protocol
  • 11 FHIR resource types supported

πŸ”’ Compliance & Security

  • HIPAA-Eligible Services: AWS HealthLake with encryption
  • No Real PHI: All testing uses Synthea-generated synthetic data
  • Audit Logging: Complete trail via CloudWatch
  • IAM Least Privilege: Minimal permissions for Lambda roles
  • Encryption: DynamoDB and HealthLake encryption enabled
  • Human Review Required: System assists; final decisions by clinicians

πŸ—ΊοΈ Roadmap

  • Core AI agent with Mistral Large 2
  • FHIR R4 integration with HealthLake
  • Multi-persona frontend (CRC, StudyAdmin, PI)
  • Production deployment with custom domain
  • Batch patient screening
  • Advanced lab value criteria (complex ranges)
  • Multi-site enrollment coordination
  • Real-time HealthLake event triggers
  • IRB submission automation

πŸ’‘ Use Cases

  1. Clinical Research Sites: Screen patients for active trials
  2. Pharmaceutical Companies: Accelerate Phase II/III enrollment
  3. Academic Medical Centers: Match patients across trial portfolios
  4. Contract Research Organizations: Multi-site enrollment management
  5. Patient Recruitment Services: Targeted outreach campaigns

🀝 Contributing

This project was built for the AWS AI Agent Global Hackathon 2025. Contributions are welcome!

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit changes (git commit -m 'Add AmazingFeature')
  4. Push to branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

MIT License - See LICENSE file for details.

For commercial use or questions about licensing, please contact the project maintainers.


πŸ“š Documentation


πŸ™ Acknowledgments

  • AWS AI Agent Global Hackathon 2025 for the opportunity
  • Amazon Bedrock team for Mistral Large 2 integration
  • AWS HealthLake team for FHIR R4 support
  • Synthea for synthetic patient data generation
  • Samyama.ai for project sponsorship

πŸ“ž Contact

Organization: Samyama.ai

GitHub:

Live Demo: enrollment.samyama.care


Built with ❀️ for AWS AI Agent Global Hackathon 2025

AWS Bedrock FHIR R4 HIPAA

⭐ Star this repo β€’ πŸ”— Live Demo β€’ πŸ“Ί Demo Video

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages