AI

Learn how to integrate artificial intelligence capabilities into your Medict applications.

Overview

Medict provides powerful AI capabilities to enhance healthcare workflows, including natural language processing, clinical decision support, and automated data extraction.

AI Services

Natural Language Processing

Process clinical text and extract structured data:

import { MedictClient } from '@medplum/core';

const client = new MedictClient({
  baseUrl: 'https://api.medplum.com',
  clientId: 'your-client-id'
});

// Extract entities from clinical text
async function extractEntities(text) {
  const result = await client.request('POST', '/ai/extract-entities', {
    text: text,
    entityTypes: ['symptoms', 'medications', 'conditions', 'procedures']
  });
  
  return result;
}

// Example usage
const clinicalNote = "Patient presents with chest pain and shortness of breath. Taking metoprolol 50mg daily.";
const entities = await extractEntities(clinicalNote);
console.log(entities);
// Output: {
//   symptoms: ['chest pain', 'shortness of breath'],
//   medications: ['metoprolol 50mg'],
//   conditions: [],
//   procedures: []
// }

Clinical Decision Support

Get AI-powered clinical recommendations:

// Get clinical recommendations
async function getClinicalRecommendations(patientId, symptoms) {
  const result = await client.request('POST', '/ai/clinical-recommendations', {
    patientId: patientId,
    symptoms: symptoms,
    includeDifferentialDiagnosis: true,
    includeTreatmentOptions: true
  });
  
  return result;
}

// Example usage
const recommendations = await getClinicalRecommendations('patient-123', [
  'chest pain',
  'shortness of breath'
]);

console.log(recommendations);
// Output: {
//   differentialDiagnosis: [
//     { condition: 'Myocardial Infarction', probability: 0.8 },
//     { condition: 'Angina', probability: 0.6 }
//   ],
//   treatmentOptions: [
//     { treatment: 'ECG', priority: 'high' },
//     { treatment: 'Cardiac enzymes', priority: 'high' }
//   ]
// }

Automated Coding

Convert clinical text to standardized codes:

// Convert text to ICD-10 codes
async function codeToICD10(text) {
  const result = await client.request('POST', '/ai/code-icd10', {
    text: text,
    confidenceThreshold: 0.8
  });
  
  return result;
}

// Example usage
const diagnosis = "Patient has acute myocardial infarction";
const codes = await codeToICD10(diagnosis);
console.log(codes);
// Output: [
//   { code: 'I21.9', description: 'Acute myocardial infarction, unspecified', confidence: 0.95 }
// ]

AI-Powered Workflows

Automated Chart Review

// Review patient chart for completeness
async function reviewChart(patientId) {
  const result = await client.request('POST', '/ai/chart-review', {
    patientId: patientId,
    checkCompleteness: true,
    checkAccuracy: true,
    suggestImprovements: true
  });
  
  return result;
}

// Example usage
const review = await reviewChart('patient-123');
console.log(review);
// Output: {
//   completeness: {
//     score: 0.85,
//     missingFields: ['allergies', 'medications']
//   },
//   accuracy: {
//     score: 0.92,
//     inconsistencies: []
//   },
//   suggestions: [
//     'Consider adding allergy information',
//     'Update medication list with current prescriptions'
//   ]
// }

Risk Stratification

// Assess patient risk levels
async function assessRisk(patientId) {
  const result = await client.request('POST', '/ai/risk-assessment', {
    patientId: patientId,
    riskFactors: ['age', 'comorbidities', 'medications', 'vitalSigns']
  });
  
  return result;
}

// Example usage
const riskAssessment = await assessRisk('patient-123');
console.log(riskAssessment);
// Output: {
//   overallRisk: 'moderate',
//   riskScore: 0.65,
//   riskFactors: [
//     { factor: 'age', impact: 'high', value: 75 },
//     { factor: 'diabetes', impact: 'medium', value: true }
//   ],
//   recommendations: [
//     'Increase monitoring frequency',
//     'Consider specialist referral'
//   ]
// }

Automated Documentation

// Generate clinical documentation
async function generateDocumentation(encounterId, template) {
  const result = await client.request('POST', '/ai/generate-documentation', {
    encounterId: encounterId,
    template: template,
    includeRecommendations: true
  });
  
  return result;
}

// Example usage
const documentation = await generateDocumentation('encounter-123', 'progress-note');
console.log(documentation);
// Output: {
//   content: 'Patient presents with...',
//   recommendations: [
//     'Continue current medication',
//     'Schedule follow-up in 2 weeks'
//   ],
//   confidence: 0.88
// }

Machine Learning Models

Custom Model Training

// Train a custom model
async function trainModel(trainingData, modelType) {
  const result = await client.request('POST', '/ai/train-model', {
    trainingData: trainingData,
    modelType: modelType,
    parameters: {
      epochs: 100,
      learningRate: 0.001,
      batchSize: 32
    }
  });
  
  return result;
}

// Example usage
const trainingData = [
  { input: 'chest pain', output: 'cardiac' },
  { input: 'headache', output: 'neurological' }
];

const model = await trainModel(trainingData, 'classification');
console.log(model);
// Output: {
//   modelId: 'model-123',
//   accuracy: 0.92,
//   status: 'training'
// }

Model Prediction

// Make predictions with trained model
async function predict(modelId, input) {
  const result = await client.request('POST', '/ai/predict', {
    modelId: modelId,
    input: input
  });
  
  return result;
}

// Example usage
const prediction = await predict('model-123', 'chest pain');
console.log(prediction);
// Output: {
//   prediction: 'cardiac',
//   confidence: 0.89,
//   probabilities: {
//     cardiac: 0.89,
//     neurological: 0.05,
//     respiratory: 0.06
//   }
// }

AI Integration Examples

Smart Forms

// AI-powered form completion
function SmartForm({ patientId }) {
  const [formData, setFormData] = useState({});
  const [suggestions, setSuggestions] = useState([]);

  const handleInputChange = async (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    
    // Get AI suggestions
    const aiSuggestions = await client.request('POST', '/ai/form-suggestions', {
      patientId: patientId,
      field: field,
      value: value,
      context: formData
    });
    
    setSuggestions(aiSuggestions);
  };

  return (
    <div>
      <input
        value={formData.symptoms || ''}
        onChange={(e) => handleInputChange('symptoms', e.target.value)}
        placeholder="Enter symptoms..."
      />
      {suggestions.map((suggestion, index) => (
        <div key={index} onClick={() => setFormData(prev => ({ ...prev, symptoms: suggestion }))}>
          {suggestion}
        </div>
      ))}
    </div>
  );
}

Clinical Alerts

// AI-powered clinical alerts
async function checkClinicalAlerts(patientId) {
  const alerts = await client.request('POST', '/ai/clinical-alerts', {
    patientId: patientId,
    alertTypes: ['drug-interactions', 'allergy-warnings', 'risk-factors']
  });
  
  return alerts;
}

// Example usage
const alerts = await checkClinicalAlerts('patient-123');
console.log(alerts);
// Output: [
//   {
//     type: 'drug-interaction',
//     severity: 'high',
//     message: 'Metoprolol and Verapamil may cause bradycardia',
//     medications: ['Metoprolol', 'Verapamil']
//   }
// ]

Automated Summarization

// Summarize patient data
async function summarizePatient(patientId) {
  const summary = await client.request('POST', '/ai/summarize-patient', {
    patientId: patientId,
    includeHistory: true,
    includeCurrentStatus: true,
    includeRecommendations: true
  });
  
  return summary;
}

// Example usage
const summary = await summarizePatient('patient-123');
console.log(summary);
// Output: {
//   history: '75-year-old male with diabetes and hypertension...',
//   currentStatus: 'Stable with well-controlled blood pressure...',
//   recommendations: [
//     'Continue current medication regimen',
//     'Schedule annual eye exam'
//   ]
// }

Best Practices

1. Data Privacy

  • Ensure all AI processing complies with HIPAA
  • Use encrypted data transmission
  • Implement proper access controls

2. Model Validation

  • Validate AI models with clinical experts
  • Test models on diverse patient populations
  • Monitor model performance over time

3. Human Oversight

  • Always provide human review options
  • Implement confidence thresholds
  • Allow manual override of AI recommendations

4. Error Handling

// Handle AI service errors
try {
  const result = await client.request('POST', '/ai/extract-entities', { text });
} catch (error) {
  if (error.code === 'ai-service-unavailable') {
    console.log('AI service temporarily unavailable');
    // Fallback to manual processing
  } else if (error.code === 'ai-confidence-low') {
    console.log('AI confidence too low, manual review required');
    // Flag for human review
  }
}

Next Steps