HomeDocumentation

JavaScript SDK

The Telesoft Healthcare AI JavaScript SDK makes it easy to integrate our AI capabilities into your web and Node.js applications. This SDK handles authentication, request formatting, and response parsing to streamline your development process.

Installation

Install the SDK using npm or yarn:

npm

npm install @telesoft/healthcare-ai

yarn

yarn add @telesoft/healthcare-ai

Authentication

Initialize the SDK with your API key:

import { TelesoftAI } from '@telesoft/healthcare-ai';

// Initialize the client with your API key
const telesoft = new TelesoftAI({
  apiKey: 'YOUR_API_KEY'
});

⚠️ API Key Security

Never include your API key directly in client-side code. For browser applications, make API calls through your own backend service to keep your API key secure. The SDK can be used safely in server-side environments like Node.js.

Basic Usage

Here's a simple example of using the SDK to analyze patient symptoms:

import { TelesoftAI } from '@telesoft/healthcare-ai';

// Initialize the client
const telesoft = new TelesoftAI({
  apiKey: process.env.TELESOFT_API_KEY
});

// Analyze patient symptoms
async function analyzePatientSymptoms() {
  try {
    const analysis = await telesoft.diagnostics.analyze({
      patientData: {
        age: 45,
        sex: "female",
        symptoms: ["cough", "fever", "shortness of breath"],
        duration: "5 days",
        medicalHistory: ["hypertension", "type 2 diabetes"],
        medications: ["lisinopril", "metformin"]
      },
      options: {
        includeConfidenceScores: true,
        includeDifferentialDiagnosis: true,
        includeRecommendations: true,
        includeEvidence: true
      }
    });
    
    console.log("Primary diagnosis:", analysis.primaryDiagnosis.condition);
    console.log("Confidence:", analysis.primaryDiagnosis.confidenceScore);
    console.log("Differential diagnoses:", analysis.differentialDiagnoses);
    console.log("Recommended tests:", analysis.recommendations.diagnosticTests);
    
    return analysis;
  } catch (error) {
    console.error("Error analyzing symptoms:", error);
    throw error;
  }
}

// Call the function
analyzePatientSymptoms();

TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

import { TelesoftAI, DiagnosticAnalysisRequest, DiagnosticAnalysisResponse } from '@telesoft/healthcare-ai';

// Initialize the client
const telesoft = new TelesoftAI({
  apiKey: process.env.TELESOFT_API_KEY as string
});

// Define strongly-typed request
const request: DiagnosticAnalysisRequest = {
  patientData: {
    age: 45,
    sex: "female",
    symptoms: ["cough", "fever", "shortness of breath"],
    duration: "5 days",
    medicalHistory: ["hypertension", "type 2 diabetes"],
    medications: ["lisinopril", "metformin"]
  },
  options: {
    includeConfidenceScores: true,
    includeDifferentialDiagnosis: true,
    includeRecommendations: true,
    includeEvidence: true
  }
};

// Get strongly-typed response
async function getAnalysis(): Promise<DiagnosticAnalysisResponse> {
  return await telesoft.diagnostics.analyze(request);
}

// Type-safe access to results
getAnalysis().then(analysis => {
  const primaryCondition: string = analysis.primaryDiagnosis.condition;
  const confidence: number = analysis.primaryDiagnosis.confidenceScore;
  
  // TypeScript knows the structure of differentialDiagnoses
  analysis.differentialDiagnoses.forEach(diagnosis => {
    console.log(`${diagnosis.condition}: ${diagnosis.confidenceScore * 100}%`);
  });
});

Advanced Features

Analyzing Medical Images

Use the SDK to analyze medical images (Node.js environment):

import * as fs from 'fs';
import { TelesoftAI } from '@telesoft/healthcare-ai';

const telesoft = new TelesoftAI({
  apiKey: process.env.TELESOFT_API_KEY
});

async function analyzeChestXRay(imagePath) {
  // Read the image file as a buffer
  const imageBuffer = fs.readFileSync(imagePath);
  
  // Create a form with the image data
  const analysis = await telesoft.imaging.analyze({
    imagingType: "chest-xray",
    image: imageBuffer,
    options: {
      includeAnnotations: true,
      includeHeatmap: true,
      confidenceThreshold: 0.5
    }
  });
  
  console.log("Findings:", analysis.findings);
  console.log("Annotations:", analysis.annotations);
  
  // Save the annotated image if provided
  if (analysis.annotatedImage) {
    fs.writeFileSync('annotated_xray.png', Buffer.from(analysis.annotatedImage, 'base64'));
    console.log("Annotated image saved as annotated_xray.png");
  }
  
  return analysis;
}

Custom Configuration

Configure the SDK with advanced options:

import { TelesoftAI } from '@telesoft/healthcare-ai';

const telesoft = new TelesoftAI({
  apiKey: process.env.TELESOFT_API_KEY,
  baseUrl: 'https://api.telesoft.us/v1',  // Custom API endpoint
  timeout: 30000,                         // 30 second timeout
  retryConfig: {
    maxRetries: 3,                        // Max 3 retries
    initialDelayMs: 500,                  // Start with 500ms delay
    maxDelayMs: 5000,                     // Max 5 second delay
    backoffFactor: 2,                     // Double the delay each retry
    retryStatusCodes: [429, 503]          // Only retry on these status codes
  },
  debug: process.env.NODE_ENV === 'development'  // Enable debug logging in development
});

Using with React

Here's an example of using the SDK in a React application:

import React, { useState } from 'react';

// Component for symptom analysis
function SymptomAnalyzer() {
  const [patientData, setPatientData] = useState({
    age: 45,
    sex: 'female',
    symptoms: ['cough', 'fever'],
    duration: '3 days'
  });
  const [analysis, setAnalysis] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  // Add a symptom to the list
  const addSymptom = (symptom) => {
    setPatientData(prev => ({
      ...prev,
      symptoms: [...prev.symptoms, symptom]
    }));
  };
  
  // Submit data for analysis
  const analyzeSymptoms = async () => {
    setLoading(true);
    setError(null);
    
    try {
      // Make API call to your backend service
      const response = await fetch('/api/analyze-symptoms', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ patientData })
      });
      
      if (!response.ok) {
        throw new Error('Analysis failed');
      }
      
      const result = await response.json();
      setAnalysis(result);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div>
      <h2>Symptom Analyzer</h2>
      
      {/* Patient data inputs */}
      <div>
        <label>
          Age:
          <input
            type="number"
            value={patientData.age}
            onChange={(e) => setPatientData(prev => ({
              ...prev,
              age: parseInt(e.target.value)
            }))}
          />
        </label>
        
        {/* More form inputs... */}
      </div>
      
      {/* Symptom list */}
      <div>
        <h3>Symptoms</h3>
        <ul>
          {patientData.symptoms.map((symptom, index) => (
            <li key={index}>{symptom}</li>
          ))}
        </ul>
        
        {/* Symptom input */}
        <input
          type="text"
          placeholder="Add a symptom"
          onKeyDown={(e) => {
            if (e.key === 'Enter' && e.target.value) {
              addSymptom(e.target.value);
              e.target.value = '';
            }
          }}
        />
      </div>
      
      <button 
        onClick={analyzeSymptoms}
        disabled={loading || patientData.symptoms.length === 0}
      >
        {loading ? 'Analyzing...' : 'Analyze Symptoms'}
      </button>
      
      {/* Display error */}
      {error && (
        <div className="error">
          Error: {error}
        </div>
      )}
      
      {/* Display analysis results */}
      {analysis && (
        <div className="results">
          <h3>Analysis Results</h3>
          <p>Primary diagnosis: {analysis.primaryDiagnosis.condition}</p>
          <p>Confidence: {(analysis.primaryDiagnosis.confidenceScore * 100).toFixed(1)}%</p>
          
          <h4>Differential Diagnoses</h4>
          <ul>
            {analysis.differentialDiagnoses.map((diagnosis, index) => (
              <li key={index}>
                {diagnosis.condition} ({(diagnosis.confidenceScore * 100).toFixed(1)}%)
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}

export default SymptomAnalyzer;

// Backend API route (Next.js example)
// pages/api/analyze-symptoms.js
import { TelesoftAI } from '@telesoft/healthcare-ai';

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }
  
  try {
    const { patientData } = req.body;
    
    // Initialize Telesoft client
    const telesoft = new TelesoftAI({
      apiKey: process.env.TELESOFT_API_KEY
    });
    
    // Call the Telesoft API
    const analysis = await telesoft.diagnostics.analyze({
      patientData,
      options: {
        includeConfidenceScores: true,
        includeDifferentialDiagnosis: true,
        includeRecommendations: true
      }
    });
    
    return res.status(200).json(analysis);
  } catch (error) {
    console.error('Error analyzing symptoms:', error);
    return res.status(500).json({ 
      error: 'Analysis failed', 
      message: error.message 
    });
  }
}

Handling Errors

The SDK provides structured error handling:

import { TelesoftAI, TelesoftError, AuthError, RateLimitError, ValidationError } from '@telesoft/healthcare-ai';

const telesoft = new TelesoftAI({
  apiKey: process.env.TELESOFT_API_KEY
});

async function safeAnalyze() {
  try {
    const analysis = await telesoft.diagnostics.analyze({
      patientData: {
        age: 45,
        sex: "female",
        symptoms: ["cough", "fever"]
      }
    });
    return analysis;
  } catch (error) {
    if (error instanceof AuthError) {
      console.error('Authentication error:', error.message);
      // Handle invalid API key, expired token, etc.
    } else if (error instanceof RateLimitError) {
      console.error(`Rate limit exceeded. Retry after ${error.retryAfter} seconds`);
      // Implement retry with exponential backoff
    } else if (error instanceof ValidationError) {
      console.error('Validation error:', error.message);
      error.errors.forEach(err => {
        console.error(`- ${err.field}: ${err.message}`);
      });
      // Handle input validation issues
    } else if (error instanceof TelesoftError) {
      console.error('API error:', error.message, 'Code:', error.code);
      // Handle other API errors
    } else {
      console.error('Unexpected error:', error);
      // Handle unexpected errors
    }
    throw error;
  }
}

ℹ️ Error Handling Best Practices

For rate limit errors, implement exponential backoff with jitter for retries. The SDK's built-in retry mechanism can handle this automatically.