import { BaseService, ClientConfig } from '../base'; import { CarePlanDto, FhirBundleDto, ProcessDSDto } from "./ai.dto"; /** * 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. */ export declare class AiService extends BaseService { private readonly encryptionUtilities; private readonly logger; constructor(config: ClientConfig); /** * Generates discharge summary objects from file URLs containing discharge summary documents. * * @param 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>} - API response containing the discharge summary details. * The response may include an **anomalies object**, indicating potential data conflicts when discharge summaries * for different patients are uploaded under the same `encounterId`. * The anomalies object lists the conflicting IP numbers and UHID numbers. * @throws Throws an error if validation, encryption, or the API request fails. * * @example * // 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": {} * "anomalies": { anomaliesDetected: false, ipNumbers: [], uhidNumbers: [] } * } */ generateDischargeSummary(processDSDto: ProcessDSDto): Promise<{ id?: string; dischargeSummary?: Record; extractedData?: Record; fhirBundle?: Record; encryptedResponse?: string; anomalies?: unknown; }>; /** * Extracts structured text or data from outpatient (OP) consultation documents. * * @param 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>} - API response containing the OP Case sheet details. * @throws Throws an error if validation, encryption, or the API request fails. * * @example * // 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.generateOpCaseSheetSummary(processDSDto); * console.log('Extracted OP Case Data:', extractedText); * * * // Expected Output: * Extracted OP Case Data : { * "id": "1db63a9f-ac82-41fa-b50b-69a09c2c839e", * "extractedData": { * "Patient Details": { * "Name": "MR. ARUN KUMAR MITRA", * "Age": "81 Years", * "Sex": "MALE", * "Date of Birth": "08/08/1943" * // ...other details * } * }, * "fhirBundle": {} * } */ generateOpCaseSheetSummary(processDSDto: ProcessDSDto): Promise<{ id?: string; dischargeSummary?: Record; extractedData?: Record; fhirBundle?: Record; encryptedResponse?: string; anomalies?: unknown; }>; /** * Extracts structured text or data from Radiology reports. * * @param processDSDto - The data transfer object containing: * - files?: string[] — An array of Radiology Reports 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[]>} - Resolves with the API response containing an array of extracted radiology report data. * @throws Throws an error if validation, encryption, or the API request fails. * * @example * // 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.generateRadiologyReportSummary(processDSDto); * console.log('Radiology Report Data:', extractedText); * * * // Expected Output: * Radiology Report Data : { * "id": "1db63a9f-ac82-41fa-b50b-69a09c2c839e", * "extractedData": { * "Patient Details": { * "Name": "MR. ARUN KUMAR MITRA", * "Age": "81 Years", * "Sex": "MALE", * "Date of Birth": "08/08/1943" * // ...other details * } * }, * "fhirBundle": {} * } */ generateRadiologyReportSummary(processDSDto: ProcessDSDto): Promise[]>; private validateFiles; private isBase64; private extractBase64Extension; private extractUrlExtension; private generateSummary; /** * Generates a FHIR bundle using the provided data. * * @param {FhirBundleDto} fhirBundleDto - DTO containing the necessary input for FHIR bundle generation: * - recordId - Unique identifier for the health record - optional * - enableExtraction - Flag to indicate if data extraction is enabled - mandatory * - patientDetails - Details of the patient, structured as a PatientType object * - practitionerDetails - Details of the practitioner, structured as an array of PractitionerType objects * - documentReferences - Array of document URLs to be included in the FHIR bundle * - extractedData - Parsed data from the health record, structured as a key-value object - optional * - encryptedData - Encrypted form of the health data (if applicable) - optional * - publicKey - Public key used for encryption of the data - optional * - caseType - Type of health case (e.g., OPD, IPD, EMERGENCY) - mandatory * * ** Notes ** : * - If the `enableExtraction` flag is set to false, document references and patientDetails, doctorDetails will be mandatory. * * @returns {Promise>} Promise resolving to the generated FHIR bundle response object. * * @throws {Error} Throws an error if: * - Validation of input DTO fails * - API request to generate FHIR bundle fails * - Encryption (if applicable) fails * * @example * const response = { * caseType: "DischargeSummary", * enableExtraction: true, * documentReferences: ["doc123", "doc456"], * recordId: "rec-789", * patientDetails: { * "firstName": "Ravi", * "middleName": "Kumar", * "lastName": "Sharma", * "birthDate": "1980-05-20", * // ... other patient details * }, * doctorDetails: [{ * "firstName": "Anita", * "middleName": "S.", * "lastName": "Verma", * "birthDate": "1975-08-15", * // ... other doctor details * }], * extractedData: { * patientName: "John Doe", * diagnosis: "Hypertension", * treatment: "Medication and lifestyle changes", * // ... other extracted data * }, * publicKey: "-----BEGIN PUBLIC KEY-----...", * }; * 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" } * ] * } * }, * ... * ] * } */ generateFhirBundle(fhirBundleDTO: FhirBundleDto): Promise>; /** * Partially uploads files or encrypted data to generate a daily update of a Discharge Summary. * * This method validates the input, performs encryption when necessary, and communicates * with the Discharge Summary generation API. It accepts either a pre-encrypted payload * or raw file URLs (which will be encrypted internally before uploading). * * ### Notes: * 1. Either an encrypted string or public file URLs must be provided. * 2. For the first upload of a discharge summary file, `encounterId` is optional. * For subsequent uploads, the `encounterId` from the first response must be provided. * 3. If `date` is not provided, the current timestamp will be used. * * @param {ProcessDSDto} processDSDto - Data Transfer Object containing discharge summary details. * @param {string} [processDSDto.encryptedData] - Pre-encrypted payload, if available. * @param {string[]} [processDSDto.files] - Array of public file URLs (S3/GCS/Azure) to be encrypted and uploaded. * @param {string} [processDSDto.publicKey] - Public key for encryption or verification (optional). * @param {string} [processDSDto.encounterId] - Unique identifier for the patient encounter (optional). * @param {string} [processDSDto.date] - ISO 8601 timestamp string (e.g., `2025-09-16T12:30:00Z`). * Defaults to the current time if not provided. * * @returns {Promise>} - API response containing the discharge summary details. * The response may include an **anomalies object**, indicating potential data conflicts when discharge summaries * for different patients are uploaded under the same `encounterId`. * The anomalies object lists the conflicting IP numbers and UHID numbers. * * @throws {Error} - Throws if neither `encryptedData` nor `files` are provided, or if the API request fails. * * @example * const dto: ProcessDSDto = { * files: ["https://example-bucket.s3.amazonaws.com/report1.pdf"], * date: "2025-09-16T12:30:00Z", * }; * * const response = await ai.partialUploadForDischargeSummary(dto); * console.log(response); * * // Expected Output: * { * id: "aece6ca4-2739-435d-b76c-d468738356cc", * dischargeSummary: {}, * extractedData: { * "Patient Details": { * Name: "Mr. Rajulapudi Sravand", * Age: "16 Year(s) 6 Month(s)", * Sex: "Male", * "Date of Birth": "2008-07-22", * "Date of Admission": "2025-02-10", * Address: "MANSOORABAD, Hyderabad, Telangana", * "Contact Number": "7075067559", * UHID: "KHLB.4731638", * "IP Number": "2506132", * "Marital Status": "Single" * } * // ...other details * } * "anomalies": { anomaliesDetected: false, ipNumbers: [], uhidNumbers: [] } * } */ partialUploadForDischargeSummary(processDSDto: ProcessDSDto): Promise<{ id?: string; dischargeSummary?: Record; extractedData?: Record; fhirBundle?: Record; encryptedResponse?: string; anomalies?: unknown; }>; /** * Finalizes the generation of a Discharge Summary for a given encounter. * * This method consolidates all previously uploaded partial Discharge Summaries * and generates the final Discharge Summary document. It supports workflows * where discharge details are uploaded incrementally (daily or partially) * and then finalized into a complete summary. * * The API is invoked using the provided `encounterId` with the update type * set to `GEN_DISCHARGE`. * * @param {string} encounterId - Unique identifier of the patient encounter * for which the final Discharge Summary should be generated. * * @returns {Promise>} - API response containing * the finalized Discharge Summary details and a success message. * * @throws {Error} - Throws if the API request fails. * * @example * const encounterId = "aece6ca4-2739-435d-b76c-d468738356cc"; * const response = await ai.triggerDischargeSummary(encounterId); * console.log(response); * * // Example Response: * { * dischargeSummary: { * patientDetails: { * Name: "Mr. Rajulapudi Sravand", * Age: "16 years 6 months", * Gender: "Male", * RegNo: "KHLB.4731638", * ipNo: "2506132", * admitDate: "2025-02-09", * dateOfOperation: "2025-02-09", * attendantDetails: "Not Available" * }, * // ...other details * }, * message: "Discharge for record aece6ca4-2739-435d-b76c-d468738356cc generated successfully" * } */ triggerDischargeSummary(encounterId: string, callbackUrl?: string, callbackAuthToken?: string): Promise<{ dischargeSummary: unknown; message: string; }>; /** * Generates a patient care plan by either using pre-encrypted input data * or encrypting provided files before submitting them to the API. * * @param {CarePlanDto} carePlanDto - Data Transfer Object containing care plan input details. * @param {string} [carePlanDto.encryptedData] - Pre-encrypted care plan payload (optional). * @param {string[]} [carePlanDto.files] - Array of file URLs (e.g., S3, GCS, Azure) to be encrypted and uploaded (optional). * @param {string} [carePlanDto.publicKey] - Public key for encryption or verification (optional). * * @returns {Promise<{id?: string, carePlan?: Record, encryptedResponse?: string}>} * Resolves with the API response containing the generated care plan details: * - `id` — Unique identifier of the generated care plan. * - `carePlan` — Structured care plan object containing patient details and care instructions. * - `encryptedResponse` — Encrypted API response string. * * @throws {Error} - If neither `encryptedData` nor `files` are provided, or if the API request fails. * * @example * * const dto: CarePlanDto = { * files: ["https://example-bucket.s3.amazonaws.com/careplan.pdf"], * }; * * const response = await ai.generateCarePlan(dto); * console.log(response); * * * // Example Response * * { * "id": "6cd35601-2a32-4869-bb60-b4bd89c74c45", * "carePlan": { * "patientDetails": { * "name": "RUQSANA BEGUM", * "age": "75Y(s) 6M(s) 30D(s)", * "sex": "Female", * "uhid": "MRKO2526015739", * "visitId": "IPKO2526005789", * "address": "TOLICHOWKI", * "contactNumber": "8886131115" * }, * //...otherDetails * }, * * } * */ generateCarePlan(carePlanDto: CarePlanDto): Promise<{ id?: string; carePlan?: Record; encryptedResponse?: string; }>; }