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

# EHR Agent

> Analyze comprehensive health records with AI-powered insights

The EHR Agent analyzes comprehensive electronic health records — labs, conditions, medications, imaging, genetics, and vital signs — to deliver evidence-based insights for both patients and clinicians. Analysis is backed by peer-reviewed medical literature and a curated corpus of 3,000+ clinical guidelines from leading medical societies.

## When to Use

<CardGroup cols={2}>
  <Card title="EHR Agent" icon="file-medical">
    **Best for:**

    * Comprehensive health analysis
    * Multi-system assessment
    * Complex cases with imaging/genetics
    * Pre-visit preparation

    **Input:** Full EHR data bundle
  </Card>

  <Card title="Lab Results Agent" icon="flask-vial">
    **Best for:**

    * Lab result interpretation
    * Post-visit lab review
    * Routine monitoring analysis
    * Direct lab-to-patient communication

    **Input:** Lab results + optional patient context
  </Card>
</CardGroup>

## Endpoint

```
POST https://api.heliosai.health/api/v1/agent
```

## Agent Modes

The EHR Agent supports two modes:

| Mode      | Processing Time | Cost   | Best For                                                    |
| --------- | --------------- | ------ | ----------------------------------------------------------- |
| **Light** | 5-8 minutes     | \$0.65 | Routine health summaries, standard cases                    |
| **Deep**  | 10-13 minutes   | \$3.50 | Complex cases, multi-step literature and guideline research |

<Info>
  Deep Agent runs include `researchTasks` in the response — an array of the specific research queries executed during the multi-step literature review. Light Agent responses do not include this field.
</Info>

## Request Format

```json theme={null}
{
  "webhookUrl": "https://your-server.com/webhook/helios",
  "agentType": "light",
  "data": {
    "patientInfo": {
      "age": 45,
      "gender": "male"
    },
    "recentAbnormalLabs": [
      {
        "date": "2025-01-15",
        "display": "Hemoglobin A1c",
        "value": "7.2",
        "unit": "%",
        "referenceRange": "4.0-5.6",
        "interpretation": "High"
      }
    ],
    "recentNormalLabs": [
      {
        "date": "2025-01-15",
        "display": "Sodium",
        "value": "140",
        "unit": "mEq/L",
        "referenceRange": "136-145"
      }
    ],
    "pastMedicalHistory": [
      {
        "display": "Type 2 Diabetes Mellitus",
        "clinicalStatus": "active",
        "onsetDate": "2020-03-15"
      }
    ],
    "medications": [
      {
        "medication": "Metformin 500mg",
        "status": "active",
        "dosage": "500mg",
        "frequency": "twice daily"
      }
    ],
    "vitalSigns": [
      {
        "display": "Blood Pressure",
        "value": "138/88",
        "unit": "mmHg",
        "date": "2025-01-15"
      }
    ]
  }
}
```

### Required Fields

| Field        | Type   | Description                  |
| ------------ | ------ | ---------------------------- |
| `webhookUrl` | string | HTTPS URL to receive results |
| `agentType`  | string | `"light"` or `"deep"`        |
| `data`       | object | Health data to analyze       |

### Health Data Fields

All fields in `data` are optional, but you should provide at least some health information for meaningful analysis:

| Field                | Type   | Description                          |
| -------------------- | ------ | ------------------------------------ |
| `patientInfo`        | object | Age, gender (no PHI — see below)     |
| `recentAbnormalLabs` | array  | Abnormal lab results                 |
| `recentNormalLabs`   | array  | Normal lab results                   |
| `labTrends`          | array  | Historical lab values over time      |
| `pastMedicalHistory` | array  | Conditions and diagnoses             |
| `medications`        | array  | Current and recent medications       |
| `familyHistory`      | array  | Family medical history               |
| `imagingStudies`     | array  | Imaging reports and findings         |
| `geneticData`        | array  | Genetic test results                 |
| `vitalSigns`         | array  | Recent vital sign measurements       |
| `additionalContext`  | string | Free-text clinical notes             |
| `userInstructions`   | string | Custom instructions for the analysis |

### Patient Info

| Field    | Type   | Description                                     |
| -------- | ------ | ----------------------------------------------- |
| `age`    | number | Patient age (de-identified, no DOB)             |
| `gender` | string | `"male"`, `"female"`, `"other"`, or `"unknown"` |

<Warning>
  **No PHI allowed in `patientInfo`.** Do not include name, date of birth, address, or any other personally identifiable information. Only de-identified demographic data (age, gender) is accepted.
</Warning>

### Lab Result Fields

Used for both `recentAbnormalLabs` and `recentNormalLabs`:

| Field            | Type   | Required | Description                                       |
| ---------------- | ------ | -------- | ------------------------------------------------- |
| `display`        | string | Yes      | Lab test name (e.g., "Hemoglobin A1c")            |
| `value`          | string | Yes      | Result value (e.g., "7.2")                        |
| `unit`           | string | Yes      | Unit of measurement (e.g., "%", "mg/dL")          |
| `date`           | string | No       | Date of test (ISO 8601). **Strongly recommended** |
| `referenceRange` | string | No       | Normal range (e.g., "4.0-5.6")                    |
| `interpretation` | string | No       | Abnormality flag (e.g., "High", "Low", "Normal")  |
| `id`             | string | No       | Unique identifier                                 |
| `code`           | string | No       | LOINC or other standard code                      |

### Lab Trends

Track how a lab value has changed over time:

| Field                     | Type   | Required | Description                    |
| ------------------------- | ------ | -------- | ------------------------------ |
| `code`                    | string | Yes      | Standard code for the lab test |
| `display`                 | string | Yes      | Lab test name                  |
| `values`                  | array  | Yes      | Array of historical values     |
| `values[].date`           | string | Yes      | Date of measurement            |
| `values[].value`          | string | Yes      | Result value                   |
| `values[].unit`           | string | Yes      | Unit of measurement            |
| `values[].interpretation` | string | No       | Abnormality flag               |

### Condition Fields

| Field                | Type   | Required | Description                                       |
| -------------------- | ------ | -------- | ------------------------------------------------- |
| `display`            | string | Yes      | Condition name (e.g., "Type 2 Diabetes Mellitus") |
| `clinicalStatus`     | string | Yes      | `"active"`, `"inactive"`, `"resolved"`, etc.      |
| `onsetDate`          | string | No       | When the condition started                        |
| `recordedDate`       | string | No       | When the condition was recorded                   |
| `verificationStatus` | string | No       | `"confirmed"`, `"provisional"`, etc.              |
| `id`                 | string | No       | Unique identifier                                 |
| `code`               | string | No       | ICD-10 or SNOMED code                             |

### Medication Fields

| Field        | Type   | Required | Description                            |
| ------------ | ------ | -------- | -------------------------------------- |
| `medication` | string | Yes      | Medication name and strength           |
| `status`     | string | Yes      | `"active"`, `"completed"`, `"stopped"` |
| `dosage`     | string | No       | Dosage amount                          |
| `frequency`  | string | No       | How often taken                        |
| `startDate`  | string | No       | When the medication was started        |
| `endDate`    | string | No       | When the medication was stopped        |
| `source`     | string | No       | `"statement"` or `"request"`           |
| `id`         | string | No       | Unique identifier                      |

### Family History Fields

| Field          | Type   | Required | Description                             |
| -------------- | ------ | -------- | --------------------------------------- |
| `relationship` | string | Yes      | Relationship (e.g., "Father", "Mother") |
| `condition`    | string | Yes      | Condition name                          |
| `onsetAge`     | string | No       | Age at onset                            |
| `id`           | string | No       | Unique identifier                       |

### Imaging Study Fields

| Field         | Type   | Required | Description                             |
| ------------- | ------ | -------- | --------------------------------------- |
| `type`        | string | Yes      | Study type (e.g., "CT Scan", "MRI")     |
| `description` | string | Yes      | Description of the study                |
| `date`        | string | No       | Date of study. **Strongly recommended** |
| `modality`    | string | No       | Imaging modality                        |
| `findings`    | string | No       | Radiology findings                      |
| `conclusion`  | string | No       | Radiologist's conclusion                |
| `reportText`  | string | No       | Full report text                        |
| `id`          | string | No       | Unique identifier                       |

### Genetic Data Fields

| Field            | Type   | Required | Description               |
| ---------------- | ------ | -------- | ------------------------- |
| `geneCode`       | string | Yes      | Gene code (e.g., "BRCA1") |
| `geneDisplay`    | string | Yes      | Gene display name         |
| `interpretation` | string | Yes      | Result interpretation     |
| `value`          | string | No       | Raw value                 |
| `method`         | string | No       | Testing method            |
| `date`           | string | No       | Date of test              |
| `id`             | string | No       | Unique identifier         |

### Vital Sign Fields

| Field            | Type   | Required | Description                                            |
| ---------------- | ------ | -------- | ------------------------------------------------------ |
| `display`        | string | Yes      | Vital sign name (e.g., "Blood Pressure", "Heart Rate") |
| `value`          | string | Yes      | Measurement value                                      |
| `unit`           | string | Yes      | Unit (e.g., "mmHg", "bpm")                             |
| `date`           | string | No       | Date of measurement                                    |
| `referenceRange` | string | No       | Normal range                                           |
| `interpretation` | string | No       | Abnormality flag                                       |
| `id`             | string | No       | Unique identifier                                      |

## Element Limits & Sorting

To ensure optimal analysis quality and prevent context overflow, the API applies limits to each data category. Elements are sorted by date (most recent first) before limits are applied.

| Category        | Max Elements | Date Field                    | Date Importance                              |
| --------------- | ------------ | ----------------------------- | -------------------------------------------- |
| Abnormal Labs   | 50           | `date`                        | **Expected** — labs almost always have dates |
| Normal Labs     | 15           | `date`                        | **Expected** — labs almost always have dates |
| Conditions      | 100          | `onsetDate` or `recordedDate` | Recommended                                  |
| Medications     | 30           | `startDate`                   | Recommended                                  |
| Family History  | 15           | N/A                           | N/A (no dates)                               |
| Imaging Studies | 15           | `date`                        | **Expected** — imaging always has dates      |
| Genetic Data    | No limit     | `date`                        | Recommended                                  |
| Vital Signs     | No limit     | `date`                        | Recommended                                  |

<Warning>
  **Dates are critical for accurate analysis.** The API sorts data by recency to prioritize the most recent findings. Without dates:

  * Lab results may be analyzed in the wrong order, potentially missing critical recent changes
  * Older, less relevant data may be included instead of recent findings
  * Trend analysis and temporal reasoning will be impaired

  While dates are technically optional (per FHIR), **lab results and imaging studies should always include dates** in practice. Data without dates will be deprioritized during element limiting.
</Warning>

## Error Responses

### 400 Bad Request — Validation Error

```json theme={null}
{
  "error": "Validation error",
  "details": [
    { "path": "webhookUrl", "message": "Invalid URL format" }
  ]
}
```

### 401 Unauthorized

```json theme={null}
{
  "error": "Unauthorized",
  "message": "Invalid or missing API key"
}
```

### 429 Too Many Requests

Returned when your company has reached its concurrent request limit. Includes a `Retry-After` header.

```json theme={null}
{
  "error": "Too many concurrent requests",
  "message": "You have 7 active light agent requests. Maximum is 7.",
  "activeCount": 7,
  "limit": 7
}
```

### 500 Internal Server Error

```json theme={null}
{
  "error": "Internal server error",
  "message": "An unexpected error occurred"
}
```

## Response Format

### Immediate Response (200 OK)

```json theme={null}
{
  "runId": "550e8400-e29b-41d4-a716-446655440000",
  "status": "accepted",
  "message": "Request accepted. Results will be delivered to your webhook."
}
```

### Response Headers

| Header                   | Description                                     | Example |
| ------------------------ | ----------------------------------------------- | ------- |
| `X-Concurrent-Limit`     | Maximum concurrent requests for this agent type | `7`     |
| `X-Concurrent-Active`    | Active requests (including this one)            | `3`     |
| `X-Concurrent-Remaining` | Available slots                                 | `4`     |

### Webhook Delivery

Results are delivered to your webhook URL (5-8 min for Light, 10-13 min for Deep):

**Light Agent response:**

```json theme={null}
{
  "runId": "550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "agent": "light",
  "timestamp": "2025-01-15T12:01:30.000Z",
  "sequenceNumber": 7,
  "result": {
    "selectedElements": [
      {
        "item": "Hemoglobin A1c",
        "category": "Laboratory Value",
        "patient_value": "7.2%",
        "matching_reason": "Elevated HbA1c indicates suboptimal glycemic control"
      }
    ],
    "patientResponse": "Your recent lab results show that your HbA1c level is 7.2%...",
    "clinicianResponse": "The patient presents with elevated HbA1c (7.2%) indicating suboptimal glycemic control...",
    "citations": {
      "patient": {
        "1": {
          "url": "https://pubmed.ncbi.nlm.nih.gov/12345678/",
          "title": "Glycemic Control in Type 2 Diabetes",
          "metadata": { "type": "pubmed" }
        },
        "2": {
          "url": "https://doi.org/10.2337/dc24-S006",
          "title": "ADA Standards of Care in Diabetes — Glycemic Goals",
          "metadata": {
            "type": "guideline",
            "source": "ADA",
            "doi": "10.2337/dc24-S006",
            "specialties": ["Endocrinology"]
          }
        }
      },
      "clinician": {
        "1": {
          "url": "https://pubmed.ncbi.nlm.nih.gov/87654321/",
          "title": "ADA Standards of Care 2025",
          "metadata": { "type": "pubmed" }
        },
        "2": {
          "url": "https://doi.org/10.2337/dc24-S009",
          "title": "ADA Standards of Care — Pharmacologic Approaches to Glycemic Treatment",
          "metadata": {
            "type": "guideline",
            "source": "ADA",
            "doi": "10.2337/dc24-S009",
            "specialties": ["Endocrinology"]
          }
        }
      }
    }
  }
}
```

**Deep Agent response** (includes `researchTasks`):

```json theme={null}
{
  "runId": "550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "agent": "deep",
  "timestamp": "2025-01-15T12:15:30.000Z",
  "sequenceNumber": 9,
  "result": {
    "selectedElements": [ ... ],
    "patientResponse": "Your recent lab results show...",
    "clinicianResponse": "The patient presents with...",
    "researchTasks": [
      "Research current ADA guidelines for glycemic control in Type 2 Diabetes",
      "Investigate SGLT2 inhibitor cardiovascular benefits in patients with CKD",
      "Analyze optimal statin therapy for diabetic patients with elevated LDL"
    ],
    "citations": {
      "patient": {
        "1": { "url": "https://pubmed.ncbi.nlm.nih.gov/12345678/", "title": "Glycemic Control in Type 2 Diabetes", "metadata": { "type": "pubmed" } },
        "2": {
          "url": "https://doi.org/10.2337/dc24-S006",
          "title": "ADA Standards of Care — Glycemic Goals and Hypoglycemia",
          "metadata": { "type": "guideline", "source": "ADA", "doi": "10.2337/dc24-S006", "specialties": ["Endocrinology"] }
        }
      },
      "clinician": {
        "1": { "url": "https://pubmed.ncbi.nlm.nih.gov/87654321/", "title": "ADA Standards of Care 2025", "metadata": { "type": "pubmed" } },
        "2": {
          "url": "https://doi.org/10.1161/CIR.0000000000001168",
          "title": "2023 AHA/ACC Guideline for Heart Failure Management",
          "metadata": { "type": "guideline", "source": "ACC/AHA", "doi": "10.1161/CIR.0000000000001168", "specialties": ["Cardiology"] }
        }
      }
    }
  }
}
```

### Result Fields

| Field               | Description                                       |
| ------------------- | ------------------------------------------------- |
| `selectedElements`  | Health elements selected for analysis (see below) |
| `patientResponse`   | Patient-friendly summary in Markdown              |
| `clinicianResponse` | Clinical report with citations in Markdown        |
| `citations`         | Citation metadata for both responses              |
| `researchTasks`     | Research queries executed (Deep Agent only)       |

### Selected Elements

The `selectedElements` array contains the health data elements that the AI identified as most clinically relevant:

| Field                     | Description                                                  |
| ------------------------- | ------------------------------------------------------------ |
| `ehr_element_id`          | Unique ID (e.g., "Lab 1", "Condition 3")                     |
| `ehr_element_description` | Human-readable description                                   |
| `category`                | Element category (Laboratory Value, Diagnosed Disease, etc.) |
| `patient_value`           | The patient's actual value or status                         |
| `relevance`               | Why this element was selected                                |
| `matching_reason`         | Why this element is clinically interesting                   |

## Processing Steps

Status update webhooks are sent during processing:

**Light Agent Steps:**

| Step | Name                                                   |
| ---- | ------------------------------------------------------ |
| 1    | Processing started                                     |
| 2    | Analyzing health data                                  |
| 3    | Selecting relevant elements                            |
| 4    | Researching medical literature and clinical guidelines |
| 5    | Generating patient response                            |
| 6    | Generating clinician response                          |
| 7    | Finalizing results                                     |
| 8    | Delivering final results                               |

**Deep Agent Steps:**

| Step | Name                        | Description                                          |
| ---- | --------------------------- | ---------------------------------------------------- |
| 1    | Processing started          | Request received and validated                       |
| 2    | Analyzing health data       | Extracting insights from EHR data                    |
| 3    | Selecting relevant elements | AI selecting important health elements               |
| 4    | Routing to Deep Agent       | Handing off to research agent                        |
| 5    | Starting research tasks     | Beginning parallel literature and guideline research |
| 6    | Research complete           | All research tasks finished                          |
| 7    | Generating responses        | Creating clinician and patient reports               |
| 8    | Finalizing results          | Preparing final output                               |

<Note>
  For Deep Agent, steps 1-4 are sent by the initial API server. Steps 5-8 and the final result are sent by the Deep Agent research processor. This architecture allows the Deep Agent to run for up to 16 minutes without timeout constraints.
</Note>

## Example Requests

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.heliosai.health/api/v1/agent \
    -H "Content-Type: application/json" \
    -H "x-api-key: YOUR_API_KEY" \
    -d '{
      "webhookUrl": "https://your-server.com/webhook/helios",
      "agentType": "light",
      "data": {
        "patientInfo": {
          "age": 45,
          "gender": "male"
        },
        "recentAbnormalLabs": [
          {
            "date": "2025-01-15",
            "display": "Hemoglobin A1c",
            "value": "7.2",
            "unit": "%",
            "referenceRange": "4.0-5.6",
            "interpretation": "High"
          }
        ],
        "pastMedicalHistory": [
          {
            "display": "Type 2 Diabetes Mellitus",
            "clinicalStatus": "active",
            "onsetDate": "2020-03-15"
          }
        ],
        "medications": [
          {
            "medication": "Metformin 500mg",
            "status": "active",
            "dosage": "500mg",
            "frequency": "twice daily"
          }
        ],
        "vitalSigns": [
          {
            "display": "Blood Pressure",
            "value": "138/88",
            "unit": "mmHg",
            "date": "2025-01-15"
          }
        ]
      }
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://api.heliosai.health/api/v1/agent', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      webhookUrl: 'https://your-server.com/webhook/helios',
      agentType: 'light',
      data: {
        patientInfo: { age: 45, gender: 'male' },
        recentAbnormalLabs: [
          {
            date: '2025-01-15',
            display: 'Hemoglobin A1c',
            value: '7.2',
            unit: '%',
            referenceRange: '4.0-5.6',
            interpretation: 'High'
          }
        ],
        pastMedicalHistory: [
          {
            display: 'Type 2 Diabetes Mellitus',
            clinicalStatus: 'active',
            onsetDate: '2020-03-15'
          }
        ],
        medications: [
          {
            medication: 'Metformin 500mg',
            status: 'active',
            dosage: '500mg',
            frequency: 'twice daily'
          }
        ],
        vitalSigns: [
          {
            display: 'Blood Pressure',
            value: '138/88',
            unit: 'mmHg',
            date: '2025-01-15'
          }
        ]
      }
    })
  });

  const { runId, status } = await response.json();
  console.log(`Request accepted with runId: ${runId}`);
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://api.heliosai.health/api/v1/agent',
      headers={
          'Content-Type': 'application/json',
          'x-api-key': 'YOUR_API_KEY'
      },
      json={
          'webhookUrl': 'https://your-server.com/webhook/helios',
          'agentType': 'light',
          'data': {
              'patientInfo': { 'age': 45, 'gender': 'male' },
              'recentAbnormalLabs': [
                  {
                      'date': '2025-01-15',
                      'display': 'Hemoglobin A1c',
                      'value': '7.2',
                      'unit': '%',
                      'referenceRange': '4.0-5.6',
                      'interpretation': 'High'
                  }
              ],
              'pastMedicalHistory': [
                  {
                      'display': 'Type 2 Diabetes Mellitus',
                      'clinicalStatus': 'active',
                      'onsetDate': '2020-03-15'
                  }
              ],
              'medications': [
                  {
                      'medication': 'Metformin 500mg',
                      'status': 'active',
                      'dosage': '500mg',
                      'frequency': 'twice daily'
                  }
              ],
              'vitalSigns': [
                  {
                      'display': 'Blood Pressure',
                      'value': '138/88',
                      'unit': 'mmHg',
                      'date': '2025-01-15'
                  }
              ]
          }
      }
  )

  data = response.json()
  print(f"Request accepted with runId: {data['runId']}")
  ```
</CodeGroup>

## Pricing

| Mode  | Cost               |
| ----- | ------------------ |
| Light | \$0.65 per request |
| Deep  | \$3.50 per request |

## Next Steps

<CardGroup cols={2}>
  <Card title="Webhooks" icon="webhook" href="/webhooks">
    Set up webhook handling and signature verification.
  </Card>

  <Card title="Response Format" icon="file-lines" href="/response-format">
    Learn how to parse and display responses with citations.
  </Card>

  <Card title="Rate Limits" icon="gauge" href="/rate-limits">
    Understand concurrency limits.
  </Card>

  <Card title="Lab Results Agent" icon="flask-vial" href="/api-reference/lab-results">
    Simpler endpoint for lab-only analysis.
  </Card>
</CardGroup>
