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

Getting Started

To use the SDK, you'll need an API key from the Telesoft Developer Portal:

Basic Usage

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

// Initialize the client with your API key
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.toFixed(2)}`);
    
    console.log("\nDifferential diagnoses:");
    analysis.differentialDiagnoses.forEach(diagnosis => {
      console.log(`- ${diagnosis.condition} (${diagnosis.confidenceScore.toFixed(2)})`);
    });
    
    console.log("\nRecommended tests:");
    analysis.recommendations.diagnosticTests.forEach(test => {
      console.log(`- ${test.name}: ${test.rationale}`);
    });
    
    return analysis;
  } catch (error) {
    console.error("Error analyzing patient symptoms:", error);
    throw error;
  }
}

// Call the function
analyzePatientSymptoms();

⚠️ API Key Security

Never hardcode your API key directly in your client-side code. For browser applications, use a backend proxy to make API calls. For Node.js applications, use environment variables.

Key Features

Diagnostic Analysis

Analyze patient symptoms, medical history, and demographics to generate diagnostic insights.

Medical Imaging Analysis

Analyze various medical images including X-rays, CT scans, MRIs, and more.

Treatment Recommendations

Generate evidence-based treatment recommendations based on patient data.

Medical Document Processing

Extract structured information from medical documents, reports, and notes.

Advanced Examples

Analyzing Medical Images

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

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

// Function to analyze a chest X-ray image
async function analyzeChestXray(imageFile) {
  try {
    const analysis = await telesoft.imaging.analyze({
      imagingType: "chest-xray",
      image: imageFile,
      options: {
        includeAnnotations: true,
        includeHeatmap: true,
        confidenceThreshold: 0.5
      }
    });
    
    console.log(`Found ${analysis.findings.length} findings:`);
    analysis.findings.forEach(finding => {
      console.log(`- ${finding.description} (confidence: ${finding.confidence.toFixed(2)})`);
      console.log(`  Location: ${finding.location}`);
    });
    
    // The SDK can return annotated images with findings highlighted
    if (analysis.annotatedImage) {
      // Save or display the annotated image
      console.log("Annotated image available");
    }
    
    return analysis;
  } catch (error) {
    console.error("Error analyzing chest X-ray:", error);
    throw error;
  }
}

// Example usage with file input in a browser
document.querySelector('#image-upload').addEventListener('change', async (event) => {
  const file = event.target.files[0];
  if (file) {
    try {
      const analysis = await analyzeChestXray(file);
      // Handle the analysis results
    } catch (error) {
      // Handle errors
    }
  }
});

Using with React

import React, { useState } from 'react';
import { TelesoftAI } from '@telesoft/healthcare-ai';

// Create a component that uses the Telesoft API
function SymptomAnalyzer() {
  const [symptoms, setSymptoms] = useState([]);
  const [age, setAge] = useState('');
  const [sex, setSex] = useState('');
  const [analysis, setAnalysis] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  // Function to add a symptom
  const addSymptom = (symptom) => {
    if (symptom && !symptoms.includes(symptom)) {
      setSymptoms([...symptoms, symptom]);
    }
  };
  
  // Function to remove a symptom
  const removeSymptom = (symptom) => {
    setSymptoms(symptoms.filter(s => s !== symptom));
  };
  
  // Function to analyze symptoms
  const analyzeSymptoms = async () => {
    if (!age || !sex || symptoms.length === 0) {
      setError('Please provide age, sex, and at least one symptom');
      return;
    }
    
    setLoading(true);
    setError(null);
    
    try {
      // In a real app, this request should go through your backend
      // to avoid exposing your API key in the client
      const response = await fetch('/api/analyze-symptoms', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          age: parseInt(age),
          sex,
          symptoms
        }),
      });
      
      if (!response.ok) {
        throw new Error('Failed to analyze symptoms');
      }
      
      const result = await response.json();
      setAnalysis(result);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div className="max-w-md mx-auto">
      <h2 className="text-2xl font-bold mb-4">Symptom Analyzer</h2>
      
      <div className="mb-4">
        <label className="block mb-2">Age</label>
        <input
          type="number"
          value={age}
          onChange={(e) => setAge(e.target.value)}
          className="w-full p-2 border rounded"
        />
      </div>
      
      <div className="mb-4">
        <label className="block mb-2">Sex</label>
        <select
          value={sex}
          onChange={(e) => setSex(e.target.value)}
          className="w-full p-2 border rounded"
        >
          <option value="">Select</option>
          <option value="male">Male</option>
          <option value="female">Female</option>
        </select>
      </div>
      
      <div className="mb-4">
        <label className="block mb-2">Symptoms</label>
        <div className="flex">
          <input
            id="symptom-input"
            className="flex-1 p-2 border rounded-l"
            placeholder="Enter a symptom"
          />
          <button
            onClick={() => {
              const input = document.getElementById('symptom-input');
              addSymptom(input.value);
              input.value = '';
            }}
            className="bg-primary text-white px-4 py-2 rounded-r"
          >
            Add
          </button>
        </div>
        
        <div className="mt-2">
          {symptoms.map(symptom => (
            <div
              key={symptom}
              className="inline-block bg-gray-200 text-gray-800 px-3 py-1 rounded mr-2 mb-2"
            >
              {symptom}
              <button
                onClick={() => removeSymptom(symptom)}
                className="ml-2 text-gray-600"
              >
                &times;
              </button>
            </div>
          ))}
        </div>
      </div>
      
      <button
        onClick={analyzeSymptoms}
        disabled={loading}
        className="w-full bg-primary text-white py-2 rounded"
      >
        {loading ? 'Analyzing...' : 'Analyze Symptoms'}
      </button>
      
      {error && (
        <div className="mt-4 p-3 bg-red-100 text-red-700 rounded">
          {error}
        </div>
      )}
      
      {analysis && (
        <div className="mt-6">
          <h3 className="text-xl font-bold mb-2">Analysis Results</h3>
          <div className="p-4 border rounded">
            <div className="mb-4">
              <h4 className="font-bold">Primary Diagnosis</h4>
              <p>{analysis.primaryDiagnosis.condition}</p>
              <p className="text-sm text-gray-500">
                Confidence: {(analysis.primaryDiagnosis.confidenceScore * 100).toFixed(2)}%
              </p>
            </div>
            
            {analysis.differentialDiagnoses && analysis.differentialDiagnoses.length > 0 && (
              <div>
                <h4 className="font-bold">Differential Diagnoses</h4>
                <ul className="list-disc pl-5">
                  {analysis.differentialDiagnoses.map((diagnosis, index) => (
                    <li key={index}>
                      {diagnosis.condition}
                      <span className="text-sm text-gray-500">
                        {' '}({(diagnosis.confidenceScore * 100).toFixed(2)}%)
                      </span>
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

export default SymptomAnalyzer;