@ctchealth/plato-sdk
v0.0.10
Published
A TypeScript SDK for interacting with the Plato API to create and manage AI-powered medical training simulations.
Maintainers
Keywords
Readme
Plato SDK
A TypeScript SDK for interacting with the Plato API to create and manage AI-powered medical training simulations.
Overview
The Plato SDK provides a simple and type-safe way to integrate with the Plato platform, allowing you to create medical training simulations with AI personas and manage voice-based interactions.
Features
- Create AI personas with customizable professional profiles and personalities
- Real-time voice interactions with AI assistants
- Comprehensive event system for call management
- Type-safe API with full TypeScript support
- Medical training simulation configuration
- Simulation persistence and recovery across page reloads
Installation
npm install plato-sdkQuick Start
import { PlatoApiClient } from 'plato-sdk';
// Initialize the client
const client = new PlatoApiClient({
baseUrl: 'https://your-plato-api.com',
token: 'your-api-token',
user: '[email protected]',
});
// Create a simulation
const simulation = await client.createSimulation({
persona: {
professionalProfile: {
location: 'City Hospital, New York',
practiceSettings: 'Outpatient Clinic',
yearOfExperience: 12,
specialityAndDepartment: 'Cardiology',
},
segment: SegmentType.CostConsciousPrescriber,
assistantGender: AssistantVoiceGender.Male,
name: 'Dr Vegapunk',
personalityAndBehaviour: {
riskTolerance: 40,
researchOrientation: 70,
recognitionNeed: 60,
brandLoyalty: 55,
patientEmpathy: 80,
},
context: {
subSpecialityOrTherapyFocus: 'Hypertension management',
typicalPatientMix: 'Elderly with comorbidities',
keyClinicalDrivers: 'Reducing cardiovascular risk',
},
},
product: {
name: 'Ibuprofen 1000mg',
description:
'A nonsteroidal anti-inflammatory drug used to reduce pain, inflammation, and fever',
},
presentation: 'Oral tablets, 10 tablets per pack',
scenario: 'Discussing treatment options for an elderly patient with chronic arthritis',
objectives:
'Demonstrate efficacy of Ibuprofen in pain management Highlight safety profile and contraindications Encourage patient adherence',
anticipatedObjections:
'Concerns about gastrointestinal side effects Preference for lower-cost generic alternatives Potential interactions with other medications',
});
// Check the simulation status - If simulation creation phase is equals to FINISHED, the simulation is ready to use
// If the simulation creation phase is ERROR the simulation creation failed and you need to retry creating a new one
// tip: you can also check the simulation status periodically using a polling mechanism
const status = await client.getSimulationStatus(simulation.simulationId);
// Start a voice call
const call = await client.startCall(simulation.simulationId);
// Listen to call events
call.on('call-start', () => {
console.log('Call started');
});
call.on('message', message => {
console.log('Message received:', message.transcript);
});
call.on('call-end', () => {
console.log('Call ended');
});
// Stop the call when done
call.stopCall();API Reference
PlatoApiClient
The main class for interacting with the Plato API.
Constructor
new PlatoApiClient(config: ApiClientConfig)Parameters:
config.baseUrl(string): The base URL of the Plato APIconfig.token(string): Your API authentication tokenconfig.user(string): Your user identifier
Methods
createSimulation(params: CreateSimulationDto)
Creates a new medical training simulation. It may take a few minutes for the simulation to be ready for use.
Returns: Promise<{ simulationId: string, phase: CreationPhase }>
startCall(simulationId: string)
Starts a voice call with the AI persona for the specified simulation.
Returns: Object with:
stopCall(): Function to end the callcallId: Unique identifier for the callon<K>(event: K, listener: CallEventListener<K>): Subscribe to call eventsoff<K>(event: K, listener: CallEventListener<K>): Unsubscribe from call events
getCallDetails(callId: string)
Retrieves detailed information about a completed call, including transcript, summary, recording URL, ratings, and evaluation metrics.
Parameters:
callId(string): The MongoDB_idof the call
Returns: Promise<CallDTO> — An object containing:
_id: MongoDB ID of the callsummary: Summary of the conversationtranscript: Full transcript of the callrecordingUrl: URL to access the call recordingrating: User-provided rating (0-5)successEvaluation: Boolean indicating if the call was successfulscore: Overall score for the callstrengths: Array of identified strengthsweaknesses: Array of identified weaknessesmetric1,metric2,metric3: Evaluation metric namesmetric1Value,metric2Value,metric3Value: Values for each metriccreatedAt: Timestamp when the call was createdendedAt: Timestamp when the call endedcallDurationMs: Duration of the call in milliseconds- And other call-related fields
Example:
// After a call has ended, retrieve its details
const callDetails = await client.getCallDetails(call._id);
console.log('Call Summary:', callDetails.summary);getCallRecordings(queryParams: SimulationRecordingsQueryDto)
Retrieves a paginated list of call recordings for the authenticated user.
Parameters:
queryParams(SimulationRecordingsQueryDto): Query parameters for filtering and paginationlimit(optional): Number of recordings per page (5,10, or25)page(optional): Page number for paginationsort(optional): Sort order ('asc'or'desc')
Returns: Promise<SimulationRecordingsDto[]> — An array of recording objects, each containing:
_id: MongoDB ID of the callcreatedAt: Timestamp when the call was createdrecordingStatus: Status of the recording ('STARTED','PROCESSING','FINISHED', or'FAILED')
Example:
// Get the 10 most recent call recordings
const recordings = await client.getCallRecordings({
limit: 10,
page: 1,
sort: 'desc',
});
recordings.forEach(recording => {
console.log(`Call ${recording._id} - Status: ${recording.recordingStatus}`);
});getCallRecording(callId: string)
Retrieves the recording URL for a specific call.
Parameters:
callId(string): The MongoDB_idof the call
Returns: Promise<string> — The URL to access the call recording
Example:
// Get the recording URL for a specific call
const recordingUrl = await client.getCallRecording(call._id);
console.log('Recording URL:', recordingUrl);Checking Simulation Status
You can check the current phase/status of a simulation using the checkSimulationStatus method. This is useful for polling the simulation creation process until it is ready or has failed.
const status = await client.checkSimulationStatus(simulation.simulationId);
console.log('Current phase:', status.phase); // e.g., 'FINISHED', 'ERROR', etc.- Returns:
{ phase: CreationPhase }— The current phase of the simulation creation process. - Typical usage: Poll this method until the phase is
FINISHEDorERRORbefore starting a call.
Simulation Persistence
Simulations are persisted server-side and can be recovered after page reloads. Store the simulation ID client-side (e.g., localStorage) for quick recovery.
getSimulationDetails(simulationId: string)
Retrieves detailed information about a simulation, including its original configuration.
Returns: Promise<SimulationDetailsDto> containing:
simulationId: MongoDB IDphase: Current creation phaseassistantId: The assistant ID (available after creation)configuration: OriginalCreateSimulationDtocreatedAt,updatedAt: Timestamps
Example:
// Store simulation ID after creation
const simulation = await client.createSimulation(config);
localStorage.setItem('plato_simulation_id', simulation.simulationId);
// Recover simulation on page reload
const simulationId = localStorage.getItem('plato_simulation_id');
if (simulationId) {
const details = await client.getSimulationDetails(simulationId);
if (details.phase !== CreationPhase.ERROR) {
// Resume polling if still in progress
if (details.phase !== CreationPhase.FINISHED) {
startPolling(details.simulationId);
}
} else {
localStorage.removeItem('plato_simulation_id');
}
}getUserSimulations()
Retrieves all simulations for the authenticated user. Useful when the simulation ID is not stored locally.
Returns: Promise<Array<{ simulationId: string; phase: CreationPhase }>>
Example:
const simulations = await client.getUserSimulations();
const inProgress = simulations.find(
sim => sim.phase !== CreationPhase.FINISHED && sim.phase !== CreationPhase.ERROR
);Event System
The SDK provides a comprehensive event system for managing voice calls:
Available Events
call-start: Triggered when a call beginscall-end: Triggered when a call endsspeech-start: Triggered when speech detection startsspeech-end: Triggered when speech detection endsmessage: Triggered when a message is received (contains transcript and metadata)volume-level: Triggered with volume level updates (number)error: Triggered when an error occurs
Event Usage
// Subscribe to events
call.on('message', message => {
console.log('Transcript:', message.transcript);
console.log('Type:', message.transcriptType); // 'final' or 'partial'
});
call.on('volume-level', level => {
console.log('Volume level:', level);
});
call.on('error', error => {
console.error('Call error:', error);
});Data Types
CreateSimulationDto
Configuration for creating a simulation:
interface CreateSimulationDto {
persona: CharacterCreateDto;
product: ProductConfig;
presentation?: string;
scenario: string;
objectives?: string;
anticipatedObjections?: string;
trainingConfiguration: TrainingConfigurationDto;
}CharacterCreateDto
AI persona configuration:
interface CharacterCreateDto {
name: string;
professionalProfile: ProfessionalProfileDto;
segment: SegmentType;
personalityAndBehaviour: PersonalityAndBehaviourDto;
context: ContextDto;
assistantGender?: AssistantVoiceGender;
}SimulationDetailsDto
Detailed simulation information returned by getSimulationDetails():
interface SimulationDetailsDto {
simulationId: string;
phase: CreationPhase;
assistantId: string;
configuration?: CreateSimulationDto;
createdAt: Date;
updatedAt: Date;
}CreationPhase
Enum representing the simulation creation phases:
enum CreationPhase {
STARTING = 'STARTING',
CORE = 'CORE',
BOUNDARIES = 'BOUNDARIES',
SPEECH_AND_THOUGHT = 'SPEECH_AND_THOUGHT',
CONVERSATION_EVOLUTION = 'CONVERSATION_EVOLUTION',
MEMORY = 'MEMORY',
FINISHED = 'FINISHED',
ERROR = 'ERROR',
}Error Handling
The SDK throws errors for invalid configurations and API failures:
try {
const client = new PlatoApiClient({
baseUrl: 'https://api.plato.com',
token: 'your-token',
user: 'your-user',
});
const simulation = await client.createSimulation(simulationConfig);
const call = await client.startCall(simulation.simulationId);
} catch (error) {
console.error('Error:', error.message);
}Support
For support and questions, please contact the development team.
