> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hana.health/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Reference

> Full reference for the HANA Node.js and Python SDKs. Typed, async, and built for healthcare workflows.

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @hana-health/sdk
  ```

  ```bash yarn theme={null}
  yarn add @hana-health/sdk
  ```

  ```bash pip theme={null}
  pip install hana-health
  ```
</CodeGroup>

***

## Client Initialization

<CodeGroup>
  ```javascript Node.js theme={null}
  import { HanaClient } from '@hana-health/sdk';

  const hana = new HanaClient({
    apiKey: process.env.HANA_API_KEY,  // Required
    environment: 'production',         // 'production' | 'sandbox'
    region: 'eu',                      // 'us' | 'eu' | 'uk'
    mode: 'direct',                    // 'direct' | 'connect'
    timeout: 30000,                    // Request timeout (ms)
    retries: 3                         // Auto-retry on transient failures
  });
  ```

  ```python Python theme={null}
  from hana_health import HanaClient

  hana = HanaClient(
      api_key=os.environ["HANA_API_KEY"],
      environment="production",
      region="eu",
      mode="direct",
      timeout=30,
      retries=3
  )
  ```
</CodeGroup>

| Parameter     | Type   | Default        | Description                                               |
| ------------- | ------ | -------------- | --------------------------------------------------------- |
| `apiKey`      | string | —              | Your API key (required)                                   |
| `environment` | string | `'production'` | `'production'` or `'sandbox'`                             |
| `region`      | string | `'us'`         | `'us'`, `'eu'`, `'uk'`                                    |
| `mode`        | string | `'direct'`     | `'direct'` for clinics, `'connect'` for platform partners |
| `timeout`     | number | 30000          | Request timeout in ms (Node) or seconds (Python)          |
| `retries`     | number | 3              | Auto-retry count on 5xx/timeout                           |

***

## Engagements

### `hana.engagements.create(params)`

Create a new patient engagement.

<CodeGroup>
  ```javascript Node.js theme={null}
  const engagement = await hana.engagements.create({
    patient: {
      id: 'P-12345',
      phone: '+15550123456',
      preferredChannel: 'voice',
      language: 'en'
    },
    protocol: 'medication-adherence-diabetes',
    triggerType: 'scheduled',
    scheduledAt: '2026-02-08T10:00:00Z',
    context: {
      ehrData: {
        diagnoses: [{ code: 'E11.9', description: 'Type 2 diabetes' }],
        medications: [{ name: 'Metformin', dose: '500mg', frequency: '2x daily' }]
      }
    },
    callbackUrl: 'https://your-app.com/webhooks/hana',
    whiteLabel: {                          // Optional (Connect mode)
      callerName: 'Your Health Platform',
      callerId: '+18005551234'
    }
  });

  // engagement.id → "eng_abc123"
  // engagement.status → "scheduled"
  ```

  ```python Python theme={null}
  engagement = hana.engagements.create(
      patient={
          "id": "P-12345",
          "phone": "+15550123456",
          "preferred_channel": "voice",
          "language": "en"
      },
      protocol="medication-adherence-diabetes",
      trigger_type="scheduled",
      scheduled_at="2026-02-08T10:00:00Z",
      context={
          "ehr_data": {
              "diagnoses": [{"code": "E11.9", "description": "Type 2 diabetes"}],
              "medications": [{"name": "Metformin", "dose": "500mg", "frequency": "2x daily"}]
          }
      },
      callback_url="https://your-app.com/webhooks/hana"
  )
  ```
</CodeGroup>

**Returns:** `Engagement` object with `id`, `status`, `patient_id`, `scheduled_at`, `created_at`.

### `hana.engagements.get(id)`

Retrieve an engagement by ID, including outcomes if completed.

<CodeGroup>
  ```javascript Node.js theme={null}
  const result = await hana.engagements.get('eng_abc123');

  console.log(result.status);                    // "completed"
  console.log(result.outcome.clinical_note);     // Structured clinical note
  console.log(result.outcome.tasks);             // Array of clinical tasks
  console.log(result.outcome.risk_level);        // "low" | "medium" | "high" | "critical"
  console.log(result.outcome.metrics);           // engagement_score, completion_rate, etc.
  ```

  ```python Python theme={null}
  result = hana.engagements.get("eng_abc123")

  print(result.status)
  print(result.outcome.clinical_note)
  print(result.outcome.tasks)
  print(result.outcome.risk_level)
  ```
</CodeGroup>

### `hana.engagements.list(filters)`

List engagements with filtering and pagination.

<CodeGroup>
  ```javascript Node.js theme={null}
  const page = await hana.engagements.list({
    patientId: 'P-12345',
    status: 'completed',
    from: '2026-01-01',
    to: '2026-02-07',
    limit: 20
  });

  for (const eng of page.data) {
    console.log(eng.id, eng.status, eng.completed_at);
  }

  // Paginate
  if (page.hasMore) {
    const nextPage = await hana.engagements.list({
      ...filters,
      cursor: page.cursor
    });
  }
  ```

  ```python Python theme={null}
  page = hana.engagements.list(
      patient_id="P-12345",
      status="completed",
      from_date="2026-01-01",
      to_date="2026-02-07",
      limit=20
  )

  for eng in page.data:
      print(eng.id, eng.status, eng.completed_at)
  ```
</CodeGroup>

### `hana.engagements.cancel(id)`

Cancel a scheduled engagement before it starts.

```javascript theme={null}
await hana.engagements.cancel('eng_abc123');
```

***

## Patients

### `hana.patients.upsert(id, data)`

Create or update a patient record. Upsert by your internal patient ID.

<CodeGroup>
  ```javascript Node.js theme={null}
  await hana.patients.upsert('P-12345', {
    firstName: 'Maria',
    lastName: 'Garcia',
    phone: '+15550123456',
    preferredChannel: 'voice',
    preferredLanguage: 'en',
    timezone: 'America/New_York',
    clinicalData: {
      diagnoses: [{ code: 'E11.9', description: 'Type 2 diabetes' }],
      medications: [{ name: 'Metformin', dose: '500mg', frequency: '2x daily' }]
    },
    tags: ['chronic_care', 'medication_monitoring']
  });
  ```

  ```python Python theme={null}
  hana.patients.upsert("P-12345", {
      "first_name": "Maria",
      "last_name": "Garcia",
      "phone": "+15550123456",
      "preferred_channel": "voice",
      "preferred_language": "en",
      "timezone": "America/New_York",
      "clinical_data": {
          "diagnoses": [{"code": "E11.9", "description": "Type 2 diabetes"}],
          "medications": [{"name": "Metformin", "dose": "500mg", "frequency": "2x daily"}]
      },
      "tags": ["chronic_care", "medication_monitoring"]
  })
  ```
</CodeGroup>

### `hana.patients.get(id)`

Retrieve a patient record.

### `hana.patients.getMemory(id)`

Retrieve the longitudinal engagement memory for a patient — preferences, trends, barriers, interaction patterns.

```javascript theme={null}
const memory = await hana.patients.getMemory('P-12345');

console.log(memory.preferences.bestContactTime);       // "morning"
console.log(memory.preferences.communicationStyle);     // "warm_conversational"
console.log(memory.longitudinalTrends.medicationAdherence); // [0.4, 0.5, 0.6, 0.7]
console.log(memory.activeBarriers);                     // [{ type: "cost", ... }]
```

### `hana.patients.delete(id, options)`

Delete a patient and optionally erase all data (GDPR right to erasure):

```javascript theme={null}
await hana.patients.delete('P-12345', { erase: true });
```

***

## Protocols

### `hana.protocols.create(config)`

Create a custom clinical protocol:

```javascript theme={null}
const protocol = await hana.protocols.create({
  name: 'post-surgery-day3',
  description: 'Day 3 post-surgery recovery check',
  objective: 'Assess pain, medication compliance, wound status, mobility',
  frequency: 'one_time',
  channels: ['voice', 'sms'],
  questions: [
    {
      id: 'pain',
      topic: 'pain_assessment',
      prompt: 'How would you rate your pain on a scale of 1 to 10?',
      responseType: 'numeric',
      escalationThreshold: 8
    },
    {
      id: 'medication',
      topic: 'medication_adherence',
      prompt: 'Have you been able to take your pain medication as prescribed?',
      responseType: 'boolean',
      followUpIfFalse: "What's been preventing you from taking it?"
    }
  ],
  escalationPolicy: 'clinic-post-surgical'
});
```

### `hana.protocols.list()`

List all protocols for your organization.

### `hana.protocols.upload(file)`

Upload a clinical guideline (PDF, DOCX) for HANA to parse into a structured protocol:

```javascript theme={null}
const protocol = await hana.protocols.upload({
  file: fs.readFileSync('./guidelines/palliative-care-protocol.pdf'),
  fileName: 'palliative-care-protocol.pdf',
  parseInstructions: 'Extract assessment questions, escalation criteria, and frequency guidelines'
});
```

***

## Webhooks

### `hana.webhooks.create(config)`

Register a webhook endpoint:

```javascript theme={null}
const webhook = await hana.webhooks.create({
  url: 'https://your-app.com/webhooks/hana',
  events: ['engagement.completed', 'engagement.escalated', 'clinical_note.ready'],
  secret: process.env.HANA_WEBHOOK_SECRET
});
```

### `hana.webhooks.list()`

List registered webhooks.

### `hana.webhooks.test(id)`

Send a test event to verify connectivity.

### `hana.webhooks.replay(id, eventIds)`

Replay failed webhook deliveries.

***

## Organizations (Connect Mode)

Available when `mode: 'connect'`.

### `hana.organizations.create(config)`

Create a sub-organization (for multi-tenant deployments):

```javascript theme={null}
const org = await hana.organizations.create({
  name: 'Sunrise Family Practice',
  config: {
    protocols: ['medication-adherence', 'post-visit-followup'],
    timezone: 'America/Chicago',
    language: 'en'
  },
  whiteLabel: {
    callerName: 'Sunrise Family Practice',
    callerId: '+18005552222'
  }
});
```

### `hana.organizations.list()`

List all sub-organizations under your platform.

***

## Error Handling

All SDK methods throw typed errors:

<CodeGroup>
  ```javascript Node.js theme={null}
  import { HanaError, RateLimitError, ValidationError } from '@hana-health/sdk';

  try {
    await hana.engagements.create({ ... });
  } catch (err) {
    if (err instanceof RateLimitError) {
      console.log(`Rate limited. Retry after ${err.retryAfter}s`);
    } else if (err instanceof ValidationError) {
      console.log(`Invalid field: ${err.field} — ${err.message}`);
    } else if (err instanceof HanaError) {
      console.log(`API error: ${err.code} — ${err.message}`);
    }
  }
  ```

  ```python Python theme={null}
  from hana_health.errors import HanaError, RateLimitError, ValidationError

  try:
      hana.engagements.create(...)
  except RateLimitError as e:
      print(f"Rate limited. Retry after {e.retry_after}s")
  except ValidationError as e:
      print(f"Invalid field: {e.field} — {e.message}")
  except HanaError as e:
      print(f"API error: {e.code} — {e.message}")
  ```
</CodeGroup>

***

## TypeScript Support

The Node.js SDK is fully typed. All request params and response objects have TypeScript definitions:

```typescript theme={null}
import { HanaClient, Engagement, Patient, Protocol } from '@hana-health/sdk';

const engagement: Engagement = await hana.engagements.get('eng_abc123');
const note: string = engagement.outcome.clinical_note.summary;
const tasks: Task[] = engagement.outcome.tasks;
```

<Card title="Next: API Reference" icon="book" href="/developers/api-reference">
  Full REST API documentation for direct HTTP integration.
</Card>
