CareStack EHR Node.js SDK Documentation
    Preparing search index...

    Class AiService

    AI Service for Healthcare Document Processing

    This service provides a suite of AI-powered functionalities for processing and analyzing healthcare documents. It acts as a client to an external AI API, handling tasks such as:

    Core Responsibilities:

    • Document Summarization: Generates concise summaries from clinical documents like Discharge Summaries or OP Consultations.
    • Entity Extraction: Identifies and extracts structured data (e.g., patient demographics, diagnoses, medications) from unstructured text.
    • FHIR Conversion: Transforms structured clinical data into HL7 FHIR-compliant bundles.
    • Security: Encrypts sensitive data before transmission to ensure patient privacy and compliance.

    The service uses a reactive HTTP client (e.g., WebClient in Spring) for non-blocking API communication and includes input validation mechanisms (like Jakarta Bean Validation) for robust data handling.

    Hierarchy

    • BaseService
      • AiService
    Index

    Constructors

    • Parameters

      • config: ClientConfig

      Returns AiService

    Properties

    utilities: Utilities = ...

    Methods

    • Extracts structured text or data from outpatient (OP) consultation documents.

      Parameters

      • processDSDto: ProcessDSDto

        The data transfer object containing:

        • files?: string[] — An array of OP case sheet file URLs to be encrypted (optional).
        • publicKey?: string — A public key for encrypting the response (optional).
        • encryptedData?: string — If the file content has already been encrypted, it can be passed directly (optional).

      Returns Promise<string>

      Promise - Resolves with the API response containing extracted OP consultation text or data.

      Throws an error if validation, encryption, or the API request fails.

      // Input:
      const processDSDto = {
      files: [
      'https://example-bucket.s3.amazonaws.com/op-note1.pdf',
      'https://example-bucket.s3.amazonaws.com/op-note2.pdf'
      ],
      publicKey: '-----BEGIN PUBLIC KEY-----...'
      };

      const extractedText = await ai.extractOpCaseData(processDSDto);
      console.log('Extracted OP Case Data:', extractedText);


      // Expected Output:
      Extracted OP Case Data : {
      "id": "1db63a9f-ac82-41fa-b50b-69a09c2c839e",
      "OPCaseData": {
      "patientDetails": {
      "Name": "MR. ARUN KUMAR MITRA",
      "Age": "81 Years",
      "Gender": "MALE",
      "RegNo": "600174610"
      // ...other details
      }
      },
      "extractedData": {
      "Patient Details": {
      "Name": "MR. ARUN KUMAR MITRA",
      "Age": "81 Years",
      "Sex": "MALE",
      "Date of Birth": "08/08/1943"
      // ...other details
      }
      },
      "fhirBundle": {}
      }
    • Generates discharge summary objects from file URLs containing discharge summary documents.

      Parameters

      • processDSDto: ProcessDSDto

        The data transfer object containing:

        • files?: string[] — An array of file URLs to be encrypted (optional).
        • publicKey?: string — A public key for encrypting the response (optional).
        • encryptedData?: string — If already encrypted externally, provide it directly (optional).

      Returns Promise<string>

      Promise - Resolves with the API response as a string.

      Throws an error if validation, encryption, or the API request fails.

      // Input:
      const processDSDto = {
      files: [
      'https://example-bucket.s3.amazonaws.com/discharge1.pdf',
      'https://example-bucket.s3.amazonaws.com/discharge2.pdf'
      ],
      publicKey: '-----BEGIN PUBLIC KEY-----...'
      };

      const summary = await ai.generateDischargeSummary(processDSDto);
      console.log('Discharge Summary:', summary);


      // Expected Output:
      Discharge Summary : {
      "id": "1db63a9f-ac82-41fa-b50b-69a09c2c839e",
      "dischargeSummary": {
      "patientDetails": {
      "Name": "MR. ARUN KUMAR MITRA",
      "Age": "81 Years",
      "Gender": "MALE",
      "RegNo": "600174610"
      // ...other details
      }
      },
      "extractedData": {
      "Patient Details": {
      "Name": "MR. ARUN KUMAR MITRA",
      "Age": "81 Years",
      "Sex": "MALE",
      "Date of Birth": "08/08/1943"
      // ...other details
      }
      },
      "fhirBundle": {}
      }
    • Generates a FHIR bundle using the provided data.

      Parameters

      • fhirBundleDTO: FhirBundleDto

      Returns Promise<Record<string, unknown>>

      Promise resolving to the generated FHIR bundle response object.

      Throws an error if:

      • Validation of input DTO fails
      • API request to generate FHIR bundle fails
      • Encryption (if applicable) fails
      // Input:
      const extractedData = {
      "chiefComplaints": "Severe headache and nausea for the past 1 day",
      "physicalExamination": {
      "bloodPressure": { "value": "140/90", "unit": "mmHg" },
      "heartRate": { "value": "88", "unit": "bpm" },
      "respiratoryRate": { "value": "18", "unit": "breaths/min" },
      "temperature": { "value": "98.7", "unit": "°F" },
      "oxygenSaturation": { "value": "97", "unit": "%" },
      "height": { "value": "160", "unit": "cm" },
      "weight": { "value": "60", "unit": "kg" }
      },
      "conditions": ["Migraine (suspected)"],
      "medicalHistory": [
      { "condition": "Hypothyroidism diagnosed 3 years ago", "procedure": "None" }
      ],
      "familyHistory": [
      {
      "relation": "Sister",
      "healthNote": "Diagnosed with migraine at age 22",
      "condition": "Migraine"
      }
      ],
      "allergies": ["No known drug allergies"],
      "immunizations": ["Tetanus booster taken 2 years ago, Lot number: TET987, Expiry: 2026-06-30"],
      "investigations": {
      "observations": {
      "serumCreatinine": { "value": "1.1", "unit": "mg/dL" },
      "sodium": { "value": "138", "unit": "mmol/L" },
      "potassium": { "value": "4.2", "unit": "mmol/L" }
      },
      "status": "preliminary",
      "recordedDate": "2024-07-12"
      },
      "prescribedMedications": [
      "Sumatriptan 50 mg – once at onset – oral – for migraine",
      "Ondansetron 4 mg – as needed – oral – for nausea"
      ],
      "currentProcedures": [
      {
      "description": "Appendectomy surgery",
      "complications": "No postoperative complications"
      }
      ],
      "advisoryNotes": [
      "Avoid bright lights and loud noises",
      "Take rest in a dark, quiet room during episodes"
      ],
      "followUp": [
      "Review after MRI report – OP-87954 – In-person"
      ]
      }
      }

      const dto: FhirBundleDto = {
      extractedData : extractedData
      enabledExtraction: true,
      caseType: "OPConsultation"
      patientDetails: {
      "firstName": "Ravi",
      "middleName": "Kumar",
      "lastName": "Sharma",
      "birthDate": "1980-05-20",
      // ... other patient details
      },
      practitionerDetails: [{
      "firstName": "Anita",
      "middleName": "S.",
      "lastName": "Verma",
      "birthDate": "1975-08-15",
      "gender": "female",
      "mobileNumber": "+919812345678",
      // ... other practitioner details
      }],
      };
      const response = await ai.generateFhirBundle(dto);
      console.log(response)


      // Expected Output:
      {
      resourceType: "Bundle",
      id: '7b3b5fef-7fd1-437b-940d-a55b64add446',
      meta: {
      lastUpdated: '2025-08-01T06:00:56.737721544Z',
      profile: [
      'https://nrces.in/ndhm/fhir/r4/StructureDefinition/DocumentBundle'
      ],
      security: [ [Object] ],
      versionId: '1'
      },
      identifier: {
      system: 'http://hip.in',
      value: '95328b17-adbf-49a0-b526-cd1ad8519e1c'
      },
      type: 'document',
      timestamp: '2025-08-01T06:00:56.308Z',
      entry: [
      {
      "resource": {
      "resourceType": "Patient",
      "name": [
      { "text": "John Doe" }
      ]
      }
      },
      ...
      ]
      }