### Running a FHIR Gateway Application
Source: https://github.com/dotimplement/healthchain/blob/main/healthchain/gateway/README.md
A complete example showing the setup of a FHIR gateway, registration of a read handler, and launching the application using Uvicorn.
```python
from healthchain.gateway import HealthChainAPI, FHIRGateway
from fhir.resources.patient import Patient
app = HealthChainAPI()
fhir = FHIRGateway()
fhir.add_source("main", "fhir://fhir.example.com/r4?client_id=...")
@fhir.read(Patient)
async def read_patient(patient):
return patient
app.register_gateway(fhir)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app)
```
--------------------------------
### Install HealthChain with uv
Source: https://github.com/dotimplement/healthchain/blob/main/docs/tutorials/clinicalflow/setup.md
Initializes a new project and installs the healthchain package using the uv package manager. This is the recommended approach for faster dependency management.
```bash
uv init
uv add healthchain
```
--------------------------------
### Run Complete HealthChain Example
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/discharge_summarizer.md
This snippet integrates the HealthChainAPI server and the SandboxClient to run a complete CDS Hooks example. It starts the API server in a separate thread and then uses the sandbox client to send requests and save the results. This allows for local testing of the entire integration.
```python
import uvicorn
import threading
# Start the API server in a separate thread
def start_api():
uvicorn.run(app, port=8000)
api_thread = threading.Thread(target=start_api, daemon=True)
api_thread.start()
# Send requests and save responses with sandbox client
client.send_requests()
client.save_results("./output/")
```
--------------------------------
### Execute Sandbox Workflow
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/utilities/sandbox.md
A complete example showing how to initialize the client, load data from a registry, and trigger the workflow requests.
```python
from healthchain.sandbox import SandboxClient
client = SandboxClient(
url="http://localhost:8000/cds/cds-services/my-service",
workflow="encounter-discharge"
)
client.load_from_registry(
"synthea-patient",
data_dir="./data/synthea",
resource_types=["Condition", "MedicationStatement"],
sample_size=5
)
responses = client.send_requests()
```
--------------------------------
### HealthChain Pipeline with LangChainLLM Example (Python)
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/pipeline/integrations/integrations.md
An example showcasing the integration of LangChainLLM into a HealthChain pipeline. It sets up a pipeline with a LangChain chain for summarization and demonstrates its usage.
```python
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain.llms import FakeListLLM
from healthchain.io.containers import Document
from healthchain.pipeline.base import Pipeline
from healthchain.pipeline.components.integrations import LangChainLLM
# Set up LangChain with a FakeListLLM
fake_llm = FakeListLLM(
responses=["HealthChain integrates NLP libraries for easy pipeline creation."]
)
# Define the prompt template
prompt = PromptTemplate.from_template("Summarize the following text: {text}")
# Create the LCEL chain
chain = prompt | fake_llm | StrOutputParser()
# Set up your HealthChain pipeline
pipeline = Pipeline()
pipeline.add_node(LangChainLLM(chain=chain, task="summarization"))
```
--------------------------------
### Install HealthChain using Pip
Source: https://github.com/dotimplement/healthchain/blob/main/docs/installation.md
Installs the HealthChain package from PyPI. Ensure you have pip installed and updated.
```bash
pip install healthchain
```
--------------------------------
### Install NLP Dependencies
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/pipeline/integrations/integrations.md
Commands to install required third-party NLP libraries and models via pip.
```bash
pip install spacy
python -m spacy download en_core_web_sm
pip install transformers
pip install langchain
```
--------------------------------
### Install HealthChain and NLP Dependencies
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/clinical_coding.md
Commands to install the necessary Python packages and the scispacy medical model required for clinical entity extraction.
```bash
pip install healthchain scispacy python-dotenv
pip install https://s3-us-west-2.amazonaws.com/ai2-s2-scispacy/releases/v0.5.4/en_core_sci_sm-0.5.4.tar.gz
```
--------------------------------
### Event Integration Example
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/gateway/api.md
Demonstrates how to register event handlers for specific events or event patterns.
```APIDOC
## Event Integration
### Description
This section illustrates how to integrate with the HealthChainAPI's event system by registering global event handlers using `local_handler`. Handlers can be registered for specific event names or using wildcard patterns.
### Method
N/A (Setup Code)
### Endpoint
N/A (Setup Code)
### Parameters
N/A
### Request Example
```python
from healthchain.gateway.events.dispatcher import local_handler
app = HealthChainAPI()
# Register global event handler for a specific event
@local_handler.register(event_name="fhir.patient.read")
async def log_patient_access(event):
event_name, payload = event
print(f"Patient accessed: {payload['resource_id']}")
# Register handler for all events from a specific component
@local_handler.register(event_name="cdshooks.*")
async def log_cds_events(event):
event_name, payload = event
print(f"CDS Hook fired: {event_name}")
```
### Response
N/A (Setup Code)
### Response Example
N/A (Setup Code)
```
--------------------------------
### Install HealthChain with pip
Source: https://github.com/dotimplement/healthchain/blob/main/docs/tutorials/clinicalflow/setup.md
Sets up a standard Python virtual environment and installs the healthchain package using pip. This is the traditional method for managing Python dependencies.
```bash
python -m venv .venv
source .venv/bin/activate
pip install healthchain
```
--------------------------------
### Run CDS Service with uv
Source: https://github.com/dotimplement/healthchain/blob/main/docs/tutorials/clinicalflow/testing.md
This command starts your Python application using the 'uv' ASGI server, typically used for development. Ensure your application file is named 'app.py'.
```bash
uv run python app.py
```
--------------------------------
### Scaffold and Run HealthChain Project
Source: https://github.com/dotimplement/healthchain/blob/main/README.md
Commands to initialize a new FHIR gateway project using the CLI and start the local development server.
```bash
healthchain new my-app -t fhir-gateway
cd my-app
healthchain serve
```
--------------------------------
### Advanced Workflow Example
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/gateway/cdshooks.md
Illustrates building a custom CDS Hooks workflow using adapters and pipelines for advanced clinical analysis and dynamic card generation.
```APIDOC
## Advanced Workflow Example
### Description
This example demonstrates how to build a custom CDS Hooks workflow that performs advanced clinical analysis and generates tailored decision support cards. By combining adapters and a custom pipeline, you can process incoming FHIR data, apply your own logic (such as risk assessment), and return dynamic CDS cards to the EHR.
### Method
N/A (This is a conceptual example)
### Endpoint
N/A (Assumes a registered CDS Hook endpoint)
### Parameters
N/A
### Request Example
N/A
### Response
N/A
### Code Example
```python
from healthchain.io import CdsFhirAdapter, Document
from healthchain.pipeline import Pipeline
from healthchain.pipeline.components import CdsCardCreator
from healthchain.models import CDSRequest, CDSResponse
from healthchain.gateway import HealthChainAPI, CDSHooksService
# Assume cds_service_id is the ID of your registered CDS service
# Assume pipeline_components is a list of your custom pipeline components
# Example of initializing components (replace with actual implementations)
class CustomRiskCalculator: # Placeholder
def process(self, document: Document) -> Document:
# Perform risk calculation based on document data
document.data['risk_score'] = 0.85 # Example score
return document
risk_calculator = CustomRiskCalculator()
cards_creator = CdsCardCreator()
# Define the pipeline
advanced_pipeline = Pipeline([
CdsFhirAdapter(), # Adapts incoming FHIR data
risk_calculator, # Your custom risk assessment logic
cards_creator # Creates CDS cards from results
])
app = HealthChainAPI()
cds = CDSHooksService()
@cds.hook("patient-view", id="advanced-analysis")
def run_advanced_analysis(request: CDSRequest) -> CDSResponse:
# Process the request using the advanced pipeline
# The pipeline will handle FHIR data adaptation, analysis, and card creation
# The output of the pipeline is expected to be a CDSResponse object
response: CDSResponse = advanced_pipeline.run(request)
return response
app.register_service(cds, path="/cds")
# To run this, you would typically start the HealthChainAPI application
# For example, using uvicorn:
# uvicorn your_module:app --reload
```
```
--------------------------------
### Advanced CDS Workflow Pipeline Setup
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/gateway/cdshooks.md
Shows how to set up a custom pipeline using adapters and components to process FHIR data for advanced clinical analysis.
```python
from healthchain.io import CdsFhirAdapter, Document
from healthchain.pipeline import Pipeline
from healthchain.pipeline.components import CdsCardCreator
from healthchain.models import CDSRequest, CDSResponse
from healthchain.gateway import HealthChainAPI, CDSHooksService
```
--------------------------------
### Sandbox Client Basic Usage
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/concepts.md
Provides a basic example of initializing and using the SandboxClient for testing EHR scenarios. It shows how to load test data from a registry and configure the client for a specific workflow.
```python
from healthchain.sandbox import SandboxClient
client = SandboxClient(
url="http://localhost:8000/cds/encounter-discharge",
workflow="encounter-discharge"
)
client.load_from_registry(
"synthea-patient",
data_dir="./data/synthea",
resource_types=["Condition", "DocumentReference"],
sample_size=3
)
```
--------------------------------
### Download CDS Hooks Demo Patients
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/ml_model_deployment.md
Commands to create a local directory and download pre-extracted patient JSON bundles for quick start testing.
```bash
mkdir -p cookbook/data/mimic_demo_patients
cd cookbook/data/mimic_demo_patients
wget https://github.com/dotimplement/HealthChain/raw/main/cookbook/data/mimic_demo_patients/high_risk_patient.json
wget https://github.com/dotimplement/HealthChain/raw/main/cookbook/data/mimic_demo_patients/moderate_risk_patient.json
wget https://github.com/dotimplement/HealthChain/raw/main/cookbook/data/mimic_demo_patients/low_risk_patient.json
```
--------------------------------
### Configure Epic Environment Variables
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/setup_fhir_sandboxes.md
Example configuration for a .env file to store credentials and settings required for connecting to the Epic FHIR R4 API.
```bash
EPIC_BASE_URL=https://fhir.epic.com/interconnect-fhir-oauth/api/FHIR/R4
EPIC_CLIENT_ID=your_non_production_client_id
EPIC_CLIENT_SECRET_PATH=path/to/privatekey.pem
EPIC_TOKEN_URL=https://fhir.epic.com/interconnect-fhir-oauth/oauth2/token
EPIC_USE_JWT_ASSERTION=true
EPIC_KEY_ID=healthchain-demo-key
```
--------------------------------
### Implementing a Custom CDA Parser
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/interop/parsers.md
This example shows how to create a custom parser by inheriting from the BaseParser class. This allows developers to override default parsing logic for specific document formats.
```python
from healthchain.interop import create_interop, FormatType
from healthchain.interop.config_manager import InteropConfigManager
from healthchain.interop.parsers.base import BaseParser
class CustomParser(BaseParser):
def __init__(self, config: InteropConfigManager):
super().__init__(config)
def from_string(self, data: str) -> dict:
return {"structured_data": "example"}
```
--------------------------------
### Perform Workflow Tests
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/utilities/sandbox.md
Examples for testing different workflows including CDS Hooks, Clinical Documentation (SOAP), and Free Text CSV processing.
```python
# CDS Hooks Test
client = SandboxClient(url="http://localhost:8000/cds/cds-services/sepsis-alert", workflow="patient-view")
client.load_from_registry("mimic-on-fhir", data_dir="./data/mimic-iv-fhir", resource_types=["MimicConditionED"], sample_size=5)
responses = client.send_requests()
client.save_results("./output/")
# Clinical Documentation Test
client = SandboxClient(url="http://localhost:8000/notereader/ProcessDocument/", workflow="sign-note-inpatient", protocol="soap")
client.load_from_path("./data/cda_files/", pattern="*.xml")
responses = client.send_requests()
client.save_results("./output/")
# Free Text CSV
client = SandboxClient(url="http://localhost:8000/cds/cds-services/my-service", workflow="encounter-discharge")
client.load_free_text(csv_path="./data/discharge_notes.csv", column_name="text", generate_synthetic=True)
responses = client.send_requests()
```
--------------------------------
### HealthChain Pipeline with HFTransformer Example (Python)
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/pipeline/integrations/integrations.md
An example demonstrating the integration of HFTransformer into a HealthChain pipeline for sentiment analysis. It shows pipeline setup, document processing, and accessing the model's output.
```python
from healthchain.io.containers import Document
from healthchain.pipeline.base import Pipeline
from healthchain.pipeline.components.integrations import HFTransformer
pipeline = Pipeline()
pipeline.add_node(HFTransformer.from_model_id(
task="sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english"
)
)
doc = Document("I love using HealthChain for my NLP projects!")
processed_doc = pipeline(doc)
# Access Hugging Face output
sentiment_result = processed_doc.models.get_output(
"huggingface", "sentiment-analysis"
)
print(f"Sentiment: {sentiment_result}")
```
--------------------------------
### Initialize InteropEngine
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/interop/engine.md
Demonstrates how to instantiate the InteropEngine using the factory function with default or custom configurations.
```python
from healthchain.interop import create_interop
# Create with default configuration
engine = create_interop()
# Use custom config directory
engine = create_interop(config_dir="/path/to/custom/configs")
# Create with custom validation level and environment
engine = create_interop(validation_level="warn", environment="production")
```
--------------------------------
### Configure Engine Environment and Validation
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/interop/interop.md
Demonstrates how to initialize the engine with specific environment settings and validation levels, and how to update these settings dynamically.
```python
engine = create_interop(
config_dir=Path("/path/to/custom/configs"),
validation_level="warn",
environment="production"
)
engine.config.set_environment("testing")
engine.config.set_validation_level("strict")
```
--------------------------------
### Migrating CDS Service Initialization
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/utilities/sandbox.md
Demonstrates the transition from the deprecated decorator-based class structure to the new SandboxClient instantiation. The new approach uses a client object to manage service URLs and workflow configurations directly.
```python
# Before (Deprecated)
@hc.sandbox
class TestCDS(ClinicalDecisionSupport):
@hc.ehr(workflow="patient-view")
def load_data(self):
return prefetch_data
# After
client = SandboxClient(
url="http://localhost:8000/cds/cds-services/my-service",
workflow="patient-view"
)
client.load_from_registry(
"synthea-patient",
data_dir="./data/synthea",
resource_types=["Condition", "Observation"],
sample_size=10
)
responses = client.send_requests()
```
--------------------------------
### Install Required Libraries using Pip
Source: https://github.com/dotimplement/healthchain/blob/main/docs/installation.md
Installs common libraries required by HealthChain, such as Langchain, Transformers, and PyTorch. You may need to install additional libraries based on your specific use case.
```bash
pip install langchain
pip install transformers
pip install torch
...
```
--------------------------------
### Manage Custom Configuration Templates
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/interop/interop.md
Shows how to eject built-in templates for customization using the CLI and how to initialize the engine with a custom configuration directory.
```bash
healthchain eject-templates ./my_configs
```
```python
engine = create_interop(config_dir="./my_configs")
```
--------------------------------
### Initialize Project Directory
Source: https://github.com/dotimplement/healthchain/blob/main/docs/tutorials/clinicalflow/setup.md
Creates a new directory for the project and navigates into it. This is the first step for any new HealthChain project.
```bash
mkdir clinicalflow
cd clinicalflow
```
--------------------------------
### FHIR Condition resource output example
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/pipeline/components/fhirproblemextractor.md
An example of the resulting JSON structure for a FHIR Condition resource generated by the extractor.
```json
{
"resourceType": "Condition",
"id": "hc-0aa85ff7-5e40-472b-a676-cb3df83d8313",
"clinicalStatus": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/condition-clinical",
"code": "active",
"display": "Active"
}
]
},
"code": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "C0242429",
"display": "sore throat"
}
]
},
"subject": {
"reference": "Patient/123"
}
}
```
--------------------------------
### Managing Resource Lifecycles with Context Managers
Source: https://github.com/dotimplement/healthchain/blob/main/healthchain/gateway/README.md
Demonstrates using the AsyncFHIRGateway context manager to safely handle resource creation and cleanup within a handler function.
```python
@fhir.read(Patient)
async def read_patient_and_create_note(patient):
async with fhir.resource_context("DiagnosticReport") as report:
report["subject"] = {"reference": f"Patient/{patient.id}"}
report["status"] = "final"
return patient
```
--------------------------------
### Advanced Usage: Chaining and Context Managers
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/utilities/sandbox.md
Demonstrates fluent method chaining for concise initialization and the use of context managers for automatic resource cleanup and saving.
```python
# Method Chaining
responses = (SandboxClient(url="http://localhost:8000/cds/cds-services/my-service", workflow="encounter-discharge").load_from_registry("synthea-patient", data_dir="./data/synthea", sample_size=5).send_requests())
# Context Manager
with SandboxClient(url="http://localhost:8000/cds/cds-services/my-service", workflow="encounter-discharge") as client:
client.load_free_text(csv_path="./data/notes.csv", column_name="text")
responses = client.send_requests()
```
--------------------------------
### Install HealthChain and Python-Dotenv Dependencies
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/discharge_summarizer.md
Installs the necessary HealthChain library and python-dotenv for managing environment variables. This is a prerequisite for running the CDS Hooks service.
```bash
pip install healthchain python-dotenv
```
--------------------------------
### Configure HealthChain Interop Engine
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/interop/configuration.md
Demonstrates how to initialize the Interop engine, manage environment settings, and perform runtime configuration overrides using dot notation.
```python
from healthchain.interop import create_interop
# Create an engine
engine = create_interop()
# Get a configuration value by dot notation
id_prefix = engine.config.get_config_value("defaults.common.id_prefix")
# Set the environment
engine = create_interop(environment="production")
# Set a runtime configuration override
engine.config.set_config_value("cda.sections.problems.identifiers.code", "10160-0")
```
--------------------------------
### Install HealthChain Dependencies
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/ml_model_deployment.md
Install the necessary Python packages to run the HealthChain deployment pipeline, including machine learning libraries and the core healthchain package.
```bash
pip install healthchain joblib xgboost scikit-learn python-dotenv
```
--------------------------------
### Preview and Manage Sandbox Requests
Source: https://context7.com/dotimplement/healthchain/llms.txt
Demonstrates how to preview pending requests, check status, and execute batch requests using the SandboxClient. It also covers persisting results to a local directory.
```python
previews = client.preview_requests(limit=3)
status = client.get_status()
print(f"Requests queued: {status['requests_queued']}")
responses = client.send_requests()
client.save_results("./output/")
```
--------------------------------
### Initialize and Execute SandboxClient Workflows
Source: https://github.com/dotimplement/healthchain/blob/main/docs/quickstart.md
Demonstrates how to initialize a SandboxClient, load data from a registry, and execute requests against a service. It supports both standard FHIR workflows and SOAP/CDA clinical documentation workflows.
```python
from healthchain.sandbox import SandboxClient
# Initialize client with your service URL and workflow
client = SandboxClient(
url="http://localhost:8000/cds/encounter-discharge",
workflow="encounter-discharge"
)
# Load test data from a registered dataset
client.load_from_registry(
"synthea-patient",
data_dir="./data/synthea",
resource_types=["Condition", "DocumentReference"],
sample_size=3
)
# Optionally inspect before sending
client.preview_requests()
client.get_status()
# Send requests to your service
responses = client.send_requests()
# Use context manager for automatic result saving with SOAP
with SandboxClient(
url="http://localhost:8000/notereader/ProcessDocument",
workflow="sign-note-inpatient",
protocol="soap"
) as client:
client.load_from_path("./cookbook/data/notereader_cda.xml")
responses = client.send_requests()
```
--------------------------------
### JSON: Example FHIR RiskAssessment Output
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/io/containers/dataset.md
An example of a FHIR RiskAssessment resource generated from model predictions, showcasing the structure for outcome, probability, and qualitative risk.
```json
{
"resourceType": "RiskAssessment",
"id": "hc-a1b2c3d4",
"status": "final",
"subject": {
"reference": "Patient/123"
},
"method": {
"coding": [{
"system": "https://healthchain.github.io/ml-models",
"code": "RandomForestClassifier",
"display": "RandomForestClassifier v2.1"
}]
},
"prediction": [{
"outcome": {
"coding": [{
"system": "http://hl7.org/fhir/sid/icd-10",
"code": "A41.9",
"display": "Sepsis, unspecified"
}]
},
"probabilityDecimal": 0.85,
"qualitativeRisk": {
"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/risk-probability",
"code": "high",
"display": "High Risk"
}]
}
}],
"note": [{
"text": "ML prediction: Positive (probability: 85.00%, risk: high)"
}]
}
```
--------------------------------
### NoteReaderService Integration Example
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/gateway/soap_cda.md
Example of how to integrate the NoteReaderService with HealthChainAPI to process CDA documents. This demonstrates setting up the service and defining a method to handle incoming requests.
```APIDOC
## HealthChainAPI NoteReaderService Integration
### Description
This code snippet demonstrates how to set up and use the `NoteReaderService` within the `HealthChainAPI` framework to handle SOAP/CDA workflows. It shows the basic structure for processing incoming CDA requests and returning responses.
### Method
`POST`
### Endpoint
`/soap` (when registered with HealthChainAPI)
### Parameters
#### Request Body
- **request** (CdaRequest) - Required - An object conforming to the `CdaRequest` model, containing the CDA document and associated data.
### Request Example
```python
from healthchain.gateway import HealthChainAPI, NoteReaderService
from healthchain.models import CdaRequest, CdaResponse
app = HealthChainAPI()
notes = NoteReaderService()
@notes.method("ProcessDocument")
def process_note(request: CdaRequest) -> CdaResponse:
# Your NLP pipeline here
# Example: processed_document = nlp_pipeline.process(request)
# For demonstration, returning a placeholder response
return CdaResponse(processed_data="example_processed_data")
app.register_service(notes, path="/soap")
# To run the app (example):
# if __name__ == "__main__":
# app.run(port=8000)
```
### Response
#### Success Response (200)
- **processed_data** (string) - Description of the processed data extracted from the CDA document.
#### Response Example
```json
{
"processed_data": "example_processed_data"
}
```
```
--------------------------------
### Load Data into SandboxClient
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/utilities/sandbox.md
Demonstrates various methods to populate the client with test data, including registry-based datasets, local file paths, and free-text CSV processing for synthetic FHIR generation.
```python
# Load from registry
client.load_from_registry(
"mimic-on-fhir",
data_dir="./data/mimic-fhir",
resource_types=["MimicMedication"],
sample_size=10
)
# Load from files
client.load_from_path("./data/clinical_note.xml")
# Load from CSV
client.load_free_text(
csv_path="./data/discharge_notes.csv",
column_name="text",
generate_synthetic=True,
random_seed=42
)
```
--------------------------------
### CDA Response Document Example (XML)
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/gateway/soap_cda.md
An example of a CDA document representing a response, including an extracted Medications section. This demonstrates how additional structured data can be returned.
```xml
Medications
- Lisinopril 10 mg oral tablet, once daily
```
--------------------------------
### POST /sandbox/client/initialize
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/utilities/sandbox.md
Initializes a new SandboxClient instance to manage CDS Hooks or CDA workflows.
```APIDOC
## POST /sandbox/client/initialize
### Description
Initializes the SandboxClient with a service URL and workflow type to prepare for data loading and request execution.
### Method
POST
### Endpoint
/sandbox/client/initialize
### Parameters
#### Request Body
- **url** (string) - Required - The full service URL for the CDS service.
- **workflow** (string) - Required - The workflow identifier (e.g., 'encounter-discharge', 'patient-view').
- **protocol** (string) - Optional - The communication protocol, 'rest' for CDS Hooks or 'soap' for CDA. Default is 'rest'.
- **timeout** (float) - Optional - Request timeout in seconds.
### Request Example
{
"url": "http://localhost:8000/cds/cds-services/my-service",
"workflow": "encounter-discharge",
"protocol": "rest"
}
```
--------------------------------
### Verify HealthChain Installation
Source: https://github.com/dotimplement/healthchain/blob/main/docs/tutorials/clinicalflow/setup.md
A Python script to verify the library is correctly installed by importing it and creating a simple document object. It outputs the character count of the document to confirm functionality.
```python
import healthchain
from healthchain.io import Document
doc = Document("Patient has a history of hypertension.")
print(f"Created document with {len(doc.text)} characters")
```
--------------------------------
### Install LangChain HuggingFace Dependencies
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/discharge_summarizer.md
Installs specific LangChain packages required when utilizing Hugging Face chat models for advanced prompting and LLM integration within the summarization pipeline.
```bash
pip install langchain langchain-huggingface
```
--------------------------------
### Initialize and Use FHIR Gateways
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/gateway/fhir_gateway.md
Demonstrates how to instantiate and use both synchronous and asynchronous FHIR gateways to read patient resources from a configured FHIR server.
```python
from healthchain.gateway import FHIRGateway
from fhir.resources.patient import Patient
gateway = FHIRGateway()
gateway.add_source("my_fhir_server", "fhir://fhir.example.com/api/FHIR/R4/?client_id=your_app&client_secret=secret&token_url=https://fhir.example.com/oauth2/token")
with gateway:
patient = gateway.read(Patient, "123", "my_fhir_server")
print(f"Patient: {patient.name[0].family}")
```
```python
import asyncio
from healthchain.gateway import AsyncFHIRGateway
from fhir.resources.patient import Patient
gateway = AsyncFHIRGateway()
gateway.add_source("my_fhir_server", "fhir://fhir.example.com/api/FHIR/R4/?client_id=your_app&client_secret=secret&token_url=https://fhir.example.com/oauth2/token")
async with gateway:
tasks = [
gateway.read(Patient, "123", "my_fhir_server"),
gateway.read(Patient, "456", "my_fhir_server"),
gateway.read(Patient, "789", "my_fhir_server")
]
patients = await asyncio.gather(*tasks)
for patient in patients:
print(f"Patient: {patient.name[0].family}")
```
--------------------------------
### CDA Request Document Example (XML)
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/gateway/soap_cda.md
An example of a CDA document representing a request, including sections for Problem List and Progress Note. This serves as a template for submitting clinical data.
```xml
CDA Document with Problem List and Progress Note
Progress Note
Patient's blood pressure remains elevated.
Discussed lifestyle modifications and medication adherence.
Started Lisinopril 10 mg daily for hypertension management.
```
--------------------------------
### Initialize HealthChain Gateway and FHIR Sources
Source: https://github.com/dotimplement/healthchain/blob/main/docs/quickstart.md
Demonstrates how to instantiate a HealthChainAPI application, connect multiple FHIR data sources, and define a transformation function to update patient resources.
```python
from healthchain.gateway import HealthChainAPI, FHIRGateway
from fhir.resources.patient import Patient
app = HealthChainAPI(title="My Healthcare AI App")
fhir = FHIRGateway()
fhir.add_source("epic", "fhir://fhir.epic.com/r4?client_id=...")
fhir.add_source("medplum", "fhir://api.medplum.com/fhir/R4/?client_id=...")
@fhir.transform(Patient)
def enhance_patient(id: str, source: str = None) -> Patient:
patient = fhir.read(Patient, id, source)
patient.active = True
fhir.update(patient, source)
return patient
app.register_gateway(fhir)
```
--------------------------------
### Get the Number of Entries in the FHIR Bundle
Source: https://github.com/dotimplement/healthchain/blob/main/notebooks/fhir_ml_workflow.ipynb
Calculates and returns the total number of entries within the loaded FHIR bundle. This is done by accessing the 'entry' key of the bundle dictionary and getting its length.
```python
len(bundle["entry"])
```
--------------------------------
### FHIR Error Handling Example
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/multi_ehr_aggregation.md
This example demonstrates expected error handling when querying a non-existent patient from a FHIR source, specifically Cerner. It illustrates the format of error messages encountered during FHIR requests.
```python
Error from cerner: [FHIR request failed: 400 - Unknown error]
search failed:
Resource could not be parsed or failed basic FHIR validation rules
```
--------------------------------
### YAML Status Codes Mapping Example
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/interop/mappings.md
This YAML file illustrates the mapping of clinical status codes between different healthcare formats, such as CDA and FHIR. It provides examples for active, inactive, and resolved statuses.
```yaml
# mappings/cda_fhir/status_codes.yaml
# Clinical status codes (CDA to FHIR)
"55561003":
code: "active"
display: "Active"
"73425007":
code: "inactive"
display: "Inactive"
"413322009":
code: "resolved"
display: "Resolved"
```
--------------------------------
### Initialize and Use CdsCardCreator
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/pipeline/components/cdscardcreator.md
Demonstrates how to initialize the CdsCardCreator component for model-generated outputs or static content. It shows the basic usage pattern of passing a document object to the creator instance.
```python
from healthchain.pipeline.components import CdsCardCreator
# Create cards from model output
creator = CdsCardCreator(source="huggingface", task="summarization")
doc = creator(doc) # Creates cards from model output
# Create cards with static content
creator = CdsCardCreator(static_content="Static card message")
doc = creator(doc) # Creates card with static content
```
--------------------------------
### Example RiskAssessment FHIR Resource
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/ml_model_deployment.md
Provides an example of a RiskAssessment FHIR resource, detailing its structure and key fields such as resourceType, id, subject, method, and prediction. This serves as a reference for the expected output format of the screening process.
```json
{
"resourceType": "RiskAssessment",
"id": "abc123",
"status": "final",
"subject": {
"reference": "Patient/702e11e8-6d21-41dd-9b48-31715fdc0fb1"
},
"method": {
"coding": [{
"system": "https://healthchain.io/models",
"code": "sepsis_xgboost_v1",
"display": "Sepsis XGBoost Model v1"
}]
},
"prediction": [{
"outcome": {
"coding": [{
"system": "http://hl7.org/fhir/sid/icd-10",
"code": "A41.9",
"display": "Sepsis"
}]
},
"probabilityDecimal": 0.85,
"qualitativeRisk": {
"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/risk-probability",
"code": "high",
"display": "High likelihood"
}]
}
}]
}
```
--------------------------------
### Initialize SpacyNLP Component
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/pipeline/integrations/integrations.md
Demonstrates initializing the SpacyNLP component using either a pre-configured spaCy object or the factory method with a model identifier.
```python
import spacy
from healthchain.pipeline.components.integrations import SpacyNLP
# Method 1: Using a pre-configured object
nlp = spacy.load("en_core_web_sm")
spacy_component = SpacyNLP(nlp)
# Method 2: Using the factory method
spacy_component = SpacyNLP.from_model_id("en_core_web_sm", disable=["parser"])
# Using custom local model
spacy_component = SpacyNLP.from_model_id("/path/to/your/model")
```
--------------------------------
### FHIR Condition Resource Example
Source: https://github.com/dotimplement/healthchain/blob/main/docs/cookbook/multi_ehr_aggregation.md
This snippet shows an example of a FHIR Condition resource, specifically detailing a client authorization error related to medical history. It's part of the data structures handled by the Healthchain project.
```json
{
"diagnostics": "Client not authorized for Condition - Medical History"
}
```
--------------------------------
### Initialize SandboxClient
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/utilities/sandbox.md
Configures the SandboxClient with service URL, workflow type, and communication protocol. It validates the compatibility between the chosen workflow and protocol.
```python
from healthchain.sandbox import SandboxClient
client = SandboxClient(
url="http://localhost:8000/cds/cds-services/my-service",
workflow="encounter-discharge",
protocol="rest",
timeout=10.0
)
```
--------------------------------
### Example FHIR Bundle Structure
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/utilities/fhir_helpers.md
This is an example of a FHIR Bundle resource in JSON format. It contains a collection of entries, where each entry can hold a FHIR resource. This structure is commonly used to group related healthcare information, such as patient conditions, medications, and allergies.
```json
{
"resourceType": "Bundle",
"type": "collection",
"entry": [
{
"resource": {
"resourceType": "Condition",
"id": "hc-3117bdce-bfab-4d71-968b-1ded900882ca",
"clinicalStatus": {
"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/condition-clinical",
"code": "active",
"display": "Active"
}]
},
"code": {
"coding": [{
"system": "http://snomed.info/sct",
"code": "38341003",
"display": "Hypertension"
}]
},
"subject": {"reference": "Patient/123"}
}
},
{
"resource": {
"resourceType": "Condition",
"id": "hc-9876fedc-ba98-7654-3210-fedcba987654",
"clinicalStatus": {
"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/condition-clinical",
"code": "active",
"display": "Active"
}]
},
"code": {
"coding": [{
"system": "http://snomed.info/sct",
"code": "44054006",
"display": "Diabetes"
}]
},
"subject": {"reference": "Patient/123"}
}
},
{
"resource": {
"resourceType": "MedicationStatement",
"id": "hc-86a26eba-63f9-4017-b7b2-5b36f9bad5f1",
"status": "recorded",
"medication": {
"concept": {
"coding": [{
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": "1049221",
"display": "Acetaminophen 325 MG"
}]
}
},
"subject": {"reference": "Patient/123"}
}
},
{
"resource": {
"resourceType": "AllergyIntolerance",
"id": "hc-65edab39-d90b-477b-bdb5-a173b21efd44",
"code": {
"coding": [{
"system": "http://snomed.info/sct",
"code": "418038007",
"display": "Penicillin allergy"
}]
},
"patient": {"reference": "Patient/123"}
}
}
]
}
```
--------------------------------
### Liquid Template Example for CDA to FHIR
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/interop/templates.md
An example of a Liquid template used for converting CDA (Clinical Document Architecture) data to FHIR (Fast Healthcare Interoperability Resources) format. This template demonstrates iterating through template IDs and setting resource properties.
```liquid
{
"act": {
"@classCode": "ACT",
"@moodCode": "EVN",
"templateId": [
{% for template_id in config.template.act.template_id %}
{"@root": "{{template_id}}"} {% if forloop.last != true %},{% endif %}
{% endfor %}
],
{% if resource.id %}
"id": {"@root": "{{ resource.id }}"},
{% endif %}
"code": {"@nullFlavor": "NA"},
"statusCode": {
"@code": "{{ config.template.act.status_code }}"
}
}
}
```
--------------------------------
### Perform Basic Data Conversion with InteropEngine
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/interop/interop.md
Demonstrates how to initialize the InteropEngine and perform bidirectional conversion between CDA XML and FHIR resources using the to_fhir and from_fhir methods.
```python
from healthchain.interop import create_interop, FormatType
engine = create_interop()
with open('patient_ccd.xml', 'r') as f:
cda_xml = f.read()
fhir_resources = engine.to_fhir(cda_xml, src_format="cda")
cda_document = engine.from_fhir(fhir_resources, dest_format="cda")
```
--------------------------------
### Example CDA Input for FHIR Transformation
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/interop/generators.md
This JSON object represents an example of CDA input data, specifically a 'problems' section, which is used to generate a FHIR Condition resource. It includes nested structures detailing the act, observation, and their relationships, along with codes and effective times.
```json
{
"problems": [{
'act': {
'@classCode': 'ACT',
'@moodCode': 'EVN',
'templateId': [
{'@root': '2.16.840.1.113883.10.20.1.27'},
{'@root': '1.3.6.1.4.1.19376.1.5.3.1.4.5.1'},
{'@root': '1.3.6.1.4.1.19376.1.5.3.1.4.5.2'},
{'@root': '2.16.840.1.113883.3.88.11.32.7'},
{'@root': '2.16.840.1.113883.3.88.11.83.7'}
],
'id': {
'@extension': '51854-concern',
'@root': '1.2.840.114350.1.13.525.3.7.2.768076'
},
'code': {
'@nullFlavor': 'NA'
},
'text': {
'reference': {'@value': '#problem12'}
},
'statusCode': {
'@code': 'active'
},
'effectiveTime': {
'low': {'@value': '20210317'}
},
'entryRelationship': {
'@typeCode': 'SUBJ',
'@inversionInd': False,
'observation': {
'@classCode': 'OBS',
'@moodCode': 'EVN',
'templateId': [
{'@root': '1.3.6.1.4.1.19376.1.5.3.1.4.5'},
{'@root': '2.16.840.1.113883.10.20.1.28'}
],
'id': {
'@extension': '51854',
'@root': '1.2.840.114350.1.13.525.3.7.2.768076'
},
'code': {
'@code': '64572001',
'@codeSystem': '2.16.840.1.113883.6.96',
'@codeSystemName': 'SNOMED CT'
},
'text': {
'reference': {'@value': '#problem12name'}
},
'statusCode': {
'@code': 'completed'
},
'effectiveTime': {
'low': {'@value': '20190517'}
},
'value': {
'@code': '38341003',
'@codeSystem': '2.16.840.1.113883.6.96',
'@codeSystemName': 'SNOMED CT',
'@xsi:type': 'CD',
'@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'originalText': {
'reference': {'@value': '#problem12name'}
}
},
'entryRelationship': {
'@typeCode': 'REFR',
'@inversionInd': False,
'observation': {
'@classCode': 'OBS',
'@moodCode': 'EVN',
'templateId': [
{'@root': '2.16.840.1.113883.10.20.1.50'},
{'@root': '2.16.840.1.113883.10.20.1.57'},
{'@root': '1.3.6.1.4.1.19376.1.5.3.1.4.1.1'}
],
'code': {
'@code': '33999-4',
'@codeSystem': '2.16.840.1.113883.6.1',
'@displayName': 'Status'
},
'statusCode': {
'@code': 'completed'
},
'effectiveTime': {
'low': {'@value': '20190517'}
},
'value': {
'@code': '55561003',
'@codeSystem': '2.16.840.1.113883.6.96',
'@xsi:type': 'CE',
'@displayName': 'Active',
'@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance'
}
}
}
}
}
}
}]
}
```
--------------------------------
### Integration with SummarizationPipeline
Source: https://github.com/dotimplement/healthchain/blob/main/docs/reference/pipeline/components/cdscardcreator.md
Provides an example of integrating CdsCardCreator as a component within the HealthChain SummarizationPipeline.
```APIDOC
## Integration with SummarizationPipeline
### Description
This example demonstrates how to add `CdsCardCreator` as a component to a `SummarizationPipeline`, showing its role in a larger workflow.
### Method
N/A (Python pipeline integration example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```python
from healthchain.pipeline import SummarizationPipeline
from healthchain.pipeline.components import CdsCardCreator
pipeline = SummarizationPipeline()
pipeline.add_component(CdsCardCreator(
source="huggingface",
task="summarization",
template_path="path/to/template.json",
delimiter="\n"
))
```
### Response
#### Success Response (200)
N/A (This is a Python pipeline integration example)
#### Response Example
N/A
```