Skip to content

Create @fhir.predict() decorator for simplified ML model deployment #143

@jenniferjiangkells

Description

@jenniferjiangkells

Add a convenience decorator that simplifies deploying ML models as FHIR endpoints by abstracting away the FHIR resource boilerplate.

Current approach (verbose):

from fhir.resources.reference import Reference
from fhir.resources.riskassessment import RiskAssessment

from healthchain.gateway import HealthChainAPI, FHIRGateway


app = HealthChainAPI(title="Sepsis Risk Assessment")

fhir = FHIRGateway()
fhir.add_source("epic", "fhir://epic.org/api/FHIR/R4/test")

@fhir.transform(RiskAssessment)
def sepsis_risk_transform(id: str, source: str | None = None) -> RiskAssessment:
    predicted_score = round(random(), 3)
    return RiskAssessment(
        status="completed",
        subject=Reference(reference=f"Patient/{id}"),
        prediction=[{"probabilityDecimal": predicted_score}],
    )

Proposed approach (cleaner):

@fhir.predict(resource=RiskAssessment)
def sepsis_risk(patient_id: str) -> float:
    """Just return the prediction score, decorator handles FHIR formatting."""
    # Load your model and make prediction
    return model.predict(patient_data)  # Or round(random(), 3) for testing

Goal:
Create a @fhir.predict() decorator that wraps user prediction functions and automatically:

  1. Handles FHIR resource construction
  2. Manages patient references
  3. Formats prediction output correctly
  4. Supports both sync and async functions

Implementation Location:
Add to healthchain/gateway/fhir/base.py or create healthchain/gateway/fhir/decorators.py

Acceptance Criteria:

  • Decorator accepts resource parameter (start with RiskAssessment support)
  • User function just returns prediction score (float/dict)
  • Automatically creates proper FHIR resource structure
  • Follows existing @fhir.transform() pattern for consistency
  • Works with FastAPI/uvicorn (registers as endpoint)
  • Includes type hints and docstring
  • Add unit tests in tests/gateway/
  • Add to healthchain/gateway/__init__.py exports

API Design:

def predict(
    resource: Type[DomainResource],
    status: str = "completed",
    **kwargs
) -> Callable:
    """Decorator to simplify ML model deployment as FHIR endpoints.
    
    Args:
        resource: FHIR resource type (e.g., RiskAssessment)
        status: Default status for the resource
        **kwargs: Additional resource fields
        
    Returns:
        Decorated function that returns proper FHIR resource
        
    Example:
        @fhir.predict(resource=RiskAssessment)
        def predict_sepsis(patient_id: str) -> float:
            return 0.85  # High risk
    """

Test Cases:

def test_predict_decorator_with_float():
    @fhir.predict(resource=RiskAssessment)
    def simple_prediction(patient_id: str) -> float:
        return 0.5
    
    result = simple_prediction("Patient/123")
    assert isinstance(result, RiskAssessment)
    assert result.prediction[0]["probabilityDecimal"] == 0.5

def test_predict_decorator_with_dict():
    @fhir.predict(resource=RiskAssessment)
    def complex_prediction(patient_id: str) -> dict:
        return {"score": 0.75, "confidence": 0.9}
    
    result = complex_prediction("Patient/123")
    assert result.prediction[0]["probabilityDecimal"] == 0.75

Resources:

Stretch Goals (optional):

  • Support for multiple resource types (Observation, DiagnosticReport)
  • Built-in model loading from file paths
  • Automatic input validation

Metadata

Metadata

Assignees

No one assigned

    Labels

    Component: GatewayIssue/PR that handles connections, API gatewaysgood first issueGood for newcomershacktoberfestIssues suitable for hacktoberfest

    Type

    No type

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions