HealthChain Python SDK

repository·main·Indexed 42 days ago

https://github.com/healthchainai/healthchain

An open-source Python SDK for building AI in healthcare systems. It provides type-safe FHIR tools, real-time EHR connectivity, and a gateway architecture for routing and transforming data between clinical systems. Key features include bidirectional translation between CDA and FHIR, support for CDS Hooks (encounterdischarge, orderselect, ordersign, patientview), and a FHIRToolkit for serving typed tools to AI agents via Model Context Protocol (MCP) or LangChain.

Tokens
82.4K
Snippets
264
Records
318
Agent score
53%

What's inside HealthChain

  1. Overview of HealthChain core components

    main

    HealthChain is composed of several key modules designed to facilitate healthcare data integration and agentic workflows:

    • Gateway: The central component for connecting to multiple healthcare systems and services.
    • FHIR Helpers: Utilities for creating, validating, and coding FHIR resources with type safety and minimal boilerplate.
    • Agent Tools: Typed and validated FHIR tools specifically designed for AI agents, which can be served via the Model Context Protocol (MCP) or LangChain.
    • Sandbox: A simulated Electronic Health Record (EHR) environment used to test services against realistic protocol request flows.
    • Pipeline: A framework to compose custom processing steps around your own models within protocol flows.
  2. Overview of the ClinicalFlow Tutorial

    main

    The ClinicalFlow tutorial guides you through building a Clinical Decision Support (CDS) service using HealthChain. The goal is to create a service that receives patient context from an EHR (like Epic), analyzes conditions and medications via an NLP pipeline, and returns actionable clinical alert cards.

    Core Workflow

    1. EHR System: Sends patient context (FHIR resources).
    2. CDS Service: Wraps a HealthChain Pipeline to process data.
    3. Clinical Alert Cards: The final output returned to the clinician.

    Learning Path

    • Setup: Install dependencies and create project structure.
    • FHIR Basics: Understand how FHIR resources flow into CDS Hooks requests.
    • Build Pipeline: Create an NLP pipeline to extract clinical information.
    • Create Gateway: Expose the pipeline as a CDS Hooks service.
    • Testing: Use a sandbox to validate with sample patient data.
  3. Use cases for FHIR-grounded Patient Q&A

    main

    The FHIR-grounded patient Q&A service is designed to bridge the gap between raw clinical data and patient-friendly communication. Key use cases include:

    • Patient portal chatbots: Answering questions like "what medications am I on?" or "when is my next scan?" using live FHIR records.
    • Discharge navigation: Translating discharge instructions and follow-up appointments into plain language.
    • Clinical inbox triage: Pre-generating context-aware responses to common patient messages to assist care teams.
    • Care plan explanation: Surfacing care plan steps in personalized, patient-friendly language.
  4. Understand CDA Default Mappings for FHIR translation

    main

    The cda_default mapping configuration provides the translation logic required to convert data between CDA (Clinical Document Architecture) and FHIR (Fast Healthcare Interoperability Resources) formats. These mappings are utilized by filters within the interoperability module to perform bidirectional translation:

    1. FHIR to CDA: Translates FHIR URLs to CDA OIDs and FHIR status codes to CDA status codes.
    2. CDA to FHIR: Performs a reverse lookup to map CDA OIDs back to FHIR URLs and CDA status codes back to FHIR status codes.
  5. What is a Pipeline in HealthChain?

    main

    A Pipeline in HealthChain is a sequence of processing steps designed to transform input data. In clinical NLP workflows, a pipeline typically follows this lifecycle:

    1. Input: Receives clinical text.
    2. Processing: Passes text through various NLP models or preprocessing steps.
    3. Extraction: Identifies entities such as conditions, medications, or symptoms.
    4. Output: Produces structured FHIR resources (e.g., adding entities to a problem_list).
  6. What is the HealthChain Gateway?

    main
    The HealthChain Gateway is a secure integration layer designed to connect models and agents with multiple healthcare systems. It provides a unified interface for interacting with various healthcare protocols, including FHIR RESTful APIs, CDS Hooks, and SOAP/CDA services (such as Epic NoteReader CDI). It is intended to be used alongside the HealthChainAPI to build complete healthcare integration platforms.
  7. What is a Document container?

    main

    The Document class is a container designed to manage both clinical text and structured healthcare data. It is used for clinical notes, discharge summaries, patient records, and any data that combines unstructured text with structured FHIR resources.

    A Document is organized around three primary attributes:

    1. doc.text: The raw input clinical text.
    2. doc.fhir: Manages FHIR resources, including clinical lists (problems, medications, allergies), Bundles, DocReference, and patient information.
    3. doc.cds: Manages Clinical Decision Support (CDS) outputs, such as recommendation cards and suggested actions.

    You can integrate your own NLP or ML libraries (like spaCy, HuggingFace, or LangChain) by processing doc.text and then updating the structured components via doc.update_problem_list() or by writing directly to doc.fhir.

    from healthchain.io import Document
    
    doc = Document("Patient presents with uncontrolled hypertension and Type 2 diabetes")
    # doc.text contains the string
    # doc.fhir and doc.cds provide structured management
  8. Test CDS services with the HealthChain Sandbox

    main

    The HealthChain Sandbox acts as a simulated Electronic Health Record (EHR) like Epic. It allows you to validate Clinical Decision Support (CDS) services by sending CDS Hooks requests containing realistic patient data without needing real EHR authentication or network access.

    Key capabilities include:

    • Loading test data from files or generating synthetic patients.
    • Sending CDS Hooks requests directly to your service.
    • Collecting and analyzing service responses.
  9. Format FHIR data as LLM context using a Pipeline

    main

    A HealthChain Pipeline can be used to transform a FHIR Document into a structured plain-text context block. This ensures the LLM receives human-readable clinical information instead of raw JSON.

    When a Document is initialized with a FHIR Bundle, you can use doc.fhir.get_resources("ResourceType") to extract specific resources.

    Common resources to include:

    • Condition
    • Appointment
    • CarePlan
    • MedicationRequest
    • Observation
    • DocumentReference
    from healthchain.pipeline import Pipeline
    from healthchain.io.containers import Document
    
    def create_pipeline() -> Pipeline:
        pipeline = Pipeline()
    
        @pipeline.add_node
        def format_context(doc: Document) -> Document:
            conditions = doc.fhir.get_resources("Condition")
            appointments = doc.fhir.get_resources("Appointment")
            careplans = doc.fhir.get_resources("CarePlan")
    
            lines = ["PATIENT CLINICAL CONTEXT"]
            if conditions:
                lines.append("\nDiagnoses:")
                for c in conditions:
                    onset = c.onsetDateTime
                    lines.append(
                        f"  - {c.code.text}" + (f" (since {onset})" if onset else "")
                    )
            if appointments:
                lines.append("\nUpcoming Appointments:")
                for a in appointments:
                    lines.append(f"  - {a.description}: {a.start}")
            if careplans:
                lines.append("\nCare Plan:")
                for cp in careplans:
                    lines.append(f"  {cp.description}")
    
            doc.text = "\n".join(lines)
            return doc
    
        return pipeline
    
    # Usage with a Document
    doc = Document(data=bundle)
    conditions = doc.fhir.get_resources("Condition")
  10. Understand the HealthChain configuration structure

    main

    The configuration system uses a hierarchical YAML structure. Key components include:

    • defaults.yaml: Global default values and fallback values for FHIR resources.
    • environments/: Environment-specific overrides (e.g., development.yaml, production.yaml).
    • interop/: Format-specific settings (e.g., interop/cda/).
    • mappings/: Terminology and code system mapping tables.
    • templates/: Templates for generating healthcare documents.

    CDA Configuration Loading: CDA configs are loaded from configs/interop/cda/. The directory structure determines the access key. For example:

    • configs/interop/cda/document/ccd.yaml $\rightarrow$ cda.document.ccd
    • configs/interop/cda/sections/problems.yaml $\rightarrow$ cda.sections.problems
    defaults:
      common:
        id_prefix: "hc-"
      resources:
        Condition:
          clinicalStatus:
            coding:
              - system: "http://terminology.hl7.org/CodeSystem/condition-clinical"
                code: "unknown"
                display: "Unknown"
  11. Understand Mapping Types in HealthChain

    main

    HealthChain uses mapping tables to translate between different healthcare terminology systems and formats, ensuring semantic interoperability (e.g., between CDA and FHIR).

    There are two primary mapping types:

    1. Code Systems: Maps between URI-based systems (used in FHIR) and OID-based systems (used in CDA).
      • Example: http://snomed.info/sct (FHIR) $\leftrightarrow$ 2.16.840.1.113883.6.96 (CDA).
    2. Status Codes: Maps status codes between different formats.
      • Example: active (FHIR) $\leftrightarrow$ 55561003 (CDA).
  12. Create Transform Handlers to enrich resources

    main

    Transform handlers allow you to create custom API endpoints that process and enhance FHIR resources (e.g., adding AI insights) before returning them. They are registered using the @gateway.transform(ResourceType) decorator.

    When a request is made to GET /fhir/transform/{ResourceType}/{id}?source={source}, the decorated function is executed.

    Async Transform Example

    @fhir_gateway.transform(Patient)
    async def get_enhanced_patient_summary(id: str, source: str = None) -> Patient:
        async with fhir_gateway.modify(Patient, id, source=source) as patient:
            # ... perform logic (e.g., search for observations, run NLP) ...
            patient.extension = patient.extension or []
            patient.extension.append({
                "url": "http://healthchain.org/fhir/summary",
                "valueString": "AI Insight"
            })
            return patient
    @fhir_gateway.transform(Patient)
    async def get_enhanced_patient_summary(id: str, source: str = None) -> Patient:
        async with fhir_gateway.modify(Patient, id, source=source) as patient:
            # Logic here
            return patient