@ctchealth/plato-sdk 0.0.14 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md DELETED
@@ -1,1230 +0,0 @@
1
- # Plato SDK
2
-
3
- A TypeScript SDK for interacting with the Plato API to create and manage AI-powered medical training simulations.
4
-
5
- ## Overview
6
-
7
- 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.
8
-
9
- ## Authentication
10
-
11
- All API requests require authentication using a Bearer token. Include your JWT token in the `API-AUTH` header:
12
-
13
- ```
14
- API-AUTH: Bearer <your-jwt-token>
15
- ```
16
-
17
- Requests without a valid JWT token will be rejected with a `401 Unauthorized` response.
18
-
19
- ## Features
20
-
21
- - Create AI personas with customizable professional profiles and personalities
22
- - Real-time voice interactions with AI assistants
23
- - Comprehensive event system for call management
24
- - Type-safe API with full TypeScript support
25
- - Medical training simulation configuration
26
- - Simulation persistence and recovery across page reloads
27
-
28
- ## Installation
29
-
30
- ```bash
31
- npm install plato-sdk
32
- ```
33
-
34
- ## Quick Start
35
-
36
- ```typescript
37
- import { PlatoApiClient, AvatarLanguage } from 'plato-sdk';
38
-
39
- // Initialize the client
40
- const client = new PlatoApiClient({
41
- baseUrl: 'https://your-plato-api.com',
42
- token: 'your-api-token',
43
- user: 'test@test.test',
44
- });
45
-
46
- // Get available assistant images
47
- const images = await client.getAssistantImages();
48
-
49
- // Create a simulation
50
- const simulation = await client.createSimulation({
51
- persona: {
52
- professionalProfile: {
53
- location: 'City Hospital, New York',
54
- practiceSettings: 'Outpatient Clinic',
55
- yearOfExperience: 12,
56
- specialityAndDepartment: 'Cardiology',
57
- },
58
- segment: SegmentType.CostConsciousPrescriber,
59
- assistantGender: AssistantVoiceGender.Male,
60
- name: 'Dr Vegapunk',
61
- personalityAndBehaviour: {
62
- riskTolerance: 40,
63
- researchOrientation: 70,
64
- recognitionNeed: 60,
65
- brandLoyalty: 55,
66
- patientEmpathy: 80,
67
- },
68
- context: {
69
- subSpecialityOrTherapyFocus: 'Hypertension management',
70
- typicalPatientMix: 'Elderly with comorbidities',
71
- keyClinicalDrivers: 'Reducing cardiovascular risk',
72
- },
73
- },
74
- product: {
75
- name: 'Ibuprofen 1000mg',
76
- description:
77
- 'A nonsteroidal anti-inflammatory drug used to reduce pain, inflammation, and fever',
78
- },
79
- presentation: 'Oral tablets, 10 tablets per pack',
80
- scenario: 'Discussing treatment options for an elderly patient with chronic arthritis',
81
- objectives:
82
- 'Demonstrate efficacy of Ibuprofen in pain management Highlight safety profile and contraindications Encourage patient adherence',
83
- anticipatedObjections:
84
- 'Concerns about gastrointestinal side effects Preference for lower-cost generic alternatives Potential interactions with other medications',
85
- imageId: images[0]._id,
86
- avatarLanguage: AvatarLanguage.English,
87
- });
88
-
89
- // Check the simulation status - If simulation creation phase is equals to FINISHED, the simulation is ready to use
90
- // If the simulation creation phase is ERROR the simulation creation failed and you need to retry creating a new one
91
- // tip: you can also check the simulation status periodically using a polling mechanism
92
- const status = await client.getSimulationStatus(simulation.simulationId);
93
-
94
- // Start a voice call
95
- const call = await client.startCall(simulation.simulationId);
96
-
97
- // Listen to call events
98
- call.on('call-start', () => {
99
- console.log('Call started');
100
- });
101
-
102
- call.on('message', message => {
103
- console.log('Message received:', message.transcript);
104
- });
105
-
106
- call.on('call-end', () => {
107
- console.log('Call ended - processing feedback...');
108
- });
109
-
110
- // Automatically receive post-call feedback when ready
111
- call.on('call-details-ready', callDetails => {
112
- console.log('Call Summary:', callDetails.summary);
113
- console.log('Score:', callDetails.score);
114
- console.log('Strengths:', callDetails.strengths);
115
- console.log('Areas to improve:', callDetails.weaknesses);
116
- });
117
-
118
- // Stop the call when done
119
- call.stopCall();
120
- ```
121
-
122
- ## API Reference
123
-
124
- ### PlatoApiClient
125
-
126
- The main class for interacting with the Plato API.
127
-
128
- #### Constructor
129
-
130
- ```typescript
131
- new PlatoApiClient(config: ApiClientConfig)
132
- ```
133
-
134
- **Parameters:**
135
-
136
- - `config.baseUrl` (string): The base URL of the Plato API
137
- - `config.token` (string): Your API authentication token
138
- - `config.user` (string): Your user identifier
139
- - `config.jwtToken` (string, optional): A per-user JWT token sent as the `x-client-token` header on every request
140
-
141
- **Example with JWT token:**
142
-
143
- ```typescript
144
- const client = new PlatoApiClient({
145
- baseUrl: 'https://your-plato-api.com',
146
- token: 'your-api-key',
147
- user: 'user@example.com',
148
- jwtToken: 'eyJhbGciOiJSUzI1NiIs...', // optional, per-user token
149
- });
150
- ```
151
-
152
- #### Methods
153
-
154
- ##### setJwtToken(jwtToken: string)
155
-
156
- Updates the JWT token for all subsequent requests. Use this when the token is refreshed or when switching user context.
157
-
158
- ```typescript
159
- client.setJwtToken('new-jwt-token');
160
- ```
161
-
162
- ##### clearJwtToken()
163
-
164
- Removes the JWT token from subsequent requests.
165
-
166
- ```typescript
167
- client.clearJwtToken();
168
- ```
169
-
170
- ##### createSimulation(params: CreateSimulationDto)
171
-
172
- Creates a new medical training simulation. It may take a few minutes for the simulation to be ready for use.
173
-
174
- **Returns:** `Promise<{ simulationId: string, phase: CreationPhase }>`
175
-
176
- ##### startCall(simulationId: string)
177
-
178
- Starts a voice call with the AI persona for the specified simulation.
179
-
180
- **Returns:** Object with:
181
-
182
- - `stopCall()`: Function to end the call
183
- - `callId`: Unique identifier for the call
184
- - `on<K>(event: K, listener: CallEventListener<K>)`: Subscribe to call events
185
- - `off<K>(event: K, listener: CallEventListener<K>)`: Unsubscribe from call events
186
-
187
- ##### getCallDetails(callId: string)
188
-
189
- Retrieves detailed information about a completed call, including transcript, summary, recording URL, ratings, and evaluation metrics.
190
-
191
- **Parameters:**
192
-
193
- - `callId` (string): The MongoDB `_id` of the call
194
-
195
- **Returns:** `Promise<CallDTO>` — An object containing:
196
-
197
- - `_id`: MongoDB ID of the call
198
- - `summary`: Summary of the conversation
199
- - `transcript`: Full transcript of the call
200
- - `recordingUrl`: URL to access the call recording
201
- - `rating`: User-provided rating (0-5)
202
- - `successEvaluation`: Boolean indicating if the call was successful
203
- - `score`: Overall score for the call
204
- - `strengths`: Array of identified strengths
205
- - `weaknesses`: Array of identified weaknesses
206
- - `metric1`, `metric2`, `metric3`: Evaluation metric names
207
- - `metric1Value`, `metric2Value`, `metric3Value`: Values for each metric
208
- - `createdAt`: Timestamp when the call was created
209
- - `endedAt`: Timestamp when the call ended
210
- - `callDurationMs`: Duration of the call in milliseconds
211
- - And other call-related fields
212
-
213
- **Example:**
214
-
215
- ```typescript
216
- // After a call has ended, retrieve its details
217
- const callDetails = await client.getCallDetails(call._id);
218
- console.log('Call Summary:', callDetails.summary);
219
- ```
220
-
221
- ##### getCallRecordings(queryParams: SimulationRecordingsQueryDto)
222
-
223
- Retrieves a paginated list of call recordings for the authenticated user.
224
-
225
- **Parameters:**
226
-
227
- - `queryParams` (SimulationRecordingsQueryDto): Query parameters for filtering and pagination
228
- - `limit` (optional): Number of recordings per page (`5`, `10`, or `25`)
229
- - `page` (optional): Page number for pagination
230
- - `sort` (optional): Sort order (`'asc'` or `'desc'`)
231
-
232
- **Returns:** `Promise<SimulationRecordingsDto[]>` — An array of recording objects, each containing:
233
-
234
- - `_id`: MongoDB ID of the call
235
- - `createdAt`: Timestamp when the call was created
236
- - `recordingStatus`: Status of the recording (`'STARTED'`, `'PROCESSING'`, `'FINISHED'`, or `'FAILED'`)
237
-
238
- **Example:**
239
-
240
- ```typescript
241
- // Get the 10 most recent call recordings
242
- const recordings = await client.getCallRecordings({
243
- limit: 10,
244
- page: 1,
245
- sort: 'desc',
246
- });
247
-
248
- recordings.forEach(recording => {
249
- console.log(`Call ${recording._id} - Status: ${recording.recordingStatus}`);
250
- });
251
- ```
252
-
253
- ##### getCallRecording(callId: string)
254
-
255
- Retrieves the recording URL for a specific call.
256
-
257
- **Parameters:**
258
-
259
- - `callId` (string): The MongoDB `_id` of the call
260
-
261
- **Returns:** `Promise<string>` — The URL to access the call recording
262
-
263
- **Example:**
264
-
265
- ```typescript
266
- // Get the recording URL for a specific call
267
- const recordingUrl = await client.getCallRecording(call._id);
268
- console.log('Recording URL:', recordingUrl);
269
- ```
270
-
271
- ##### uploadPdfSlides(file: File | Blob)
272
-
273
- Uploads a PDF file for slide analysis. The file will be uploaded to S3 and analyzed asynchronously.
274
-
275
- **Parameters:**
276
-
277
- - `file` (File | Blob): The PDF file to upload
278
-
279
- **Returns:** `Promise<string>` — A success message if the upload was successful.
280
-
281
- **Example:**
282
-
283
- ```typescript
284
- // Upload a PDF file from an input element
285
- const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
286
- const file = fileInput.files?.[0];
287
-
288
- if (file) {
289
- const result = await client.uploadPdfSlides(file);
290
- console.log('PDF upload initiated');
291
- }
292
- ```
293
-
294
- ##### getSlidesAnalysis(queryParams: PdfSlidesAnalysisQueryDto)
295
-
296
- Retrieves a paginated and sorted list of PDF slide analysis records.
297
-
298
- **Parameters:**
299
-
300
- - `queryParams` (PdfSlidesAnalysisQueryDto):
301
- - `limit` (optional): Number of records per page
302
- - `page` (optional): Page number
303
- - `sort` (optional): Sort order (`'asc'` or `'desc'`)
304
- - `sortBy` (optional): Field to sort by (`'createdAt'`, `'originalFilename'`, or `'totalSlides'`)
305
-
306
- **Returns:** `Promise<PdfSlidesDto[]>`
307
-
308
- **Example:**
309
-
310
- ```typescript
311
- const analysisList = await client.getSlidesAnalysis({
312
- limit: 10,
313
- page: 0,
314
- sort: 'desc',
315
- sortBy: 'createdAt',
316
- });
317
- ```
318
-
319
- ##### getSlideAnalysis(id: string)
320
-
321
- Retrieves the detailed analysis data for a specific PDF slide record, including the overview and individual slide analysis.
322
-
323
- **Parameters:**
324
-
325
- - `id` (string): The unique ID of the PDF slide record
326
-
327
- **Returns:** `Promise<PdfSlideDto>`
328
-
329
- **Example:**
330
-
331
- ```typescript
332
- const details = await client.getSlideAnalysis('pdf-slide-id');
333
- console.log('Lesson Overview:', details.lessonOverview);
334
- ```
335
-
336
- ##### deleteSlideAnalysis(id: string)
337
-
338
- Deletes a PDF slide analysis record from the database and removes the corresponding file from S3 storage.
339
-
340
- **Parameters:**
341
-
342
- - `id` (string): The unique ID of the PDF slide record to delete
343
-
344
- **Returns:** `Promise<void>`
345
-
346
- **Example:**
347
-
348
- ```typescript
349
- await client.deleteSlideAnalysis('pdf-slide-id');
350
- console.log('Analysis deleted successfully');
351
- ```
352
-
353
- ##### getAssistantImages()
354
-
355
- Retrieves all available assistant images that can be used when creating a simulation.
356
-
357
- **Returns:** `Promise<AssistantImageDto[]>` — An array of assistant image objects, each containing:
358
-
359
- - `_id`: Unique identifier for the image
360
- - `imageUrl`: URL of the assistant image
361
-
362
- **Example:**
363
-
364
- ```typescript
365
- // Get all available assistant images
366
- const images = await client.getAssistantImages();
367
- ```
368
-
369
- ##### getRecommendations()
370
-
371
- Retrieves recommendations based on the user's recent call performance. Analyzes the 5 most recent calls using a sliding window of 3 calls to identify patterns and provide actionable insights. Calls shorter than 2 minutes are excluded from analysis. No new recommendations are generated if fewer than 3 eligible calls are available.
372
-
373
- **Returns:** `Promise<RecommendationsResponseDto>` — An object containing:
374
-
375
- - `recommendations`: Array of recommendation objects, each with:
376
- - `title`: Brief title of the recommendation
377
- - `description`: Detailed, actionable description
378
- - `priority`: Priority level (`'high'`, `'medium'`, or `'low'`)
379
- - `strengths`: Array of identified strengths, each with:
380
- - `strength`: Description of the strength
381
- - `frequency`: Number of calls where this strength appeared
382
- - `improvementAreas`: Array of areas needing improvement, each with:
383
- - `area`: Description of the improvement area
384
- - `frequency`: Number of calls where this weakness appeared
385
- - `summary`: A 2-3 sentence overall summary of performance trends
386
- - `callsAnalyzed`: Number of calls that were analyzed
387
- - `generatedAt`: Timestamp when the recommendations were generated
388
-
389
- **Example:**
390
-
391
- ```typescript
392
- // Get personalized recommendations based on call history
393
- const recommendations = await client.getRecommendations();
394
-
395
- console.log(`Analyzed ${recommendations.callsAnalyzed} calls`);
396
- console.log('Summary:', recommendations.summary);
397
-
398
- // Display high-priority recommendations
399
- recommendations.recommendations
400
- .filter(rec => rec.priority === 'high')
401
- .forEach(rec => {
402
- console.log(`[HIGH] ${rec.title}: ${rec.description}`);
403
- });
404
-
405
- // Show recurring strengths
406
- recommendations.strengths.forEach(s => {
407
- console.log(`Strength (${s.frequency} calls): ${s.strength}`);
408
- });
409
-
410
- // Show areas for improvement
411
- recommendations.improvementAreas.forEach(area => {
412
- console.log(`Needs work (${area.frequency} calls): ${area.area}`);
413
- });
414
- ```
415
-
416
- **Note:** This method requires the user to have at least one completed call. If no calls are found, a `BadRequestException` will be thrown.
417
-
418
- ## Checking Simulation Status
419
-
420
- 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.
421
-
422
- ```typescript
423
- const status = await client.checkSimulationStatus(simulation.simulationId);
424
- console.log('Current phase:', status.phase); // e.g., 'FINISHED', 'ERROR', etc.
425
- ```
426
-
427
- - **Returns:** `{ phase: CreationPhase }` — The current phase of the simulation creation process.
428
- - **Typical usage:** Poll this method until the phase is `FINISHED` or `ERROR` before starting a call.
429
-
430
- ## Simulation Persistence
431
-
432
- Simulations are persisted server-side and can be recovered after page reloads. Store the simulation ID client-side (e.g., localStorage) for quick recovery.
433
-
434
- ### getSimulationDetails(simulationId: string)
435
-
436
- Retrieves detailed information about a simulation, including its original configuration.
437
-
438
- **Returns:** `Promise<SimulationDetailsDto>` containing:
439
-
440
- - `simulationId`: MongoDB ID
441
- - `phase`: Current creation phase
442
- - `assistantId`: The assistant ID (available after creation)
443
- - `configuration`: Original `CreateSimulationDto`
444
- - `createdAt`, `updatedAt`: Timestamps
445
-
446
- **Example:**
447
-
448
- ```typescript
449
- // Store simulation ID after creation
450
- const simulation = await client.createSimulation(config);
451
- localStorage.setItem('plato_simulation_id', simulation.simulationId);
452
-
453
- // Recover simulation on page reload
454
- const simulationId = localStorage.getItem('plato_simulation_id');
455
- if (simulationId) {
456
- const details = await client.getSimulationDetails(simulationId);
457
-
458
- if (details.phase !== CreationPhase.ERROR) {
459
- // Resume polling if still in progress
460
- if (details.phase !== CreationPhase.FINISHED) {
461
- startPolling(details.simulationId);
462
- }
463
- } else {
464
- localStorage.removeItem('plato_simulation_id');
465
- }
466
- }
467
- ```
468
-
469
- ### getUserSimulations()
470
-
471
- Retrieves all simulations for the authenticated user. Useful when the simulation ID is not stored locally.
472
-
473
- **Returns:** `Promise<Array<{ simulationId: string; phase: CreationPhase }>>`
474
-
475
- **Example:**
476
-
477
- ```typescript
478
- const simulations = await client.getUserSimulations();
479
- const inProgress = simulations.find(
480
- sim => sim.phase !== CreationPhase.FINISHED && sim.phase !== CreationPhase.ERROR
481
- );
482
- ```
483
-
484
- ## Call Recovery
485
-
486
- The SDK automatically handles call recovery in case of page refreshes or browser closures during active calls. This ensures that call data is never lost and all calls get properly processed by the backend, even if the page is refreshed while a call is in progress.
487
-
488
- ### How It Works
489
-
490
- When you start a call, the SDK stores minimal call state in the browser's localStorage. If the page is refreshed:
491
-
492
- 1. **On app initialization**: The `recoverAbandonedCall()` method checks for any stored call state
493
- 2. **Age-based recovery**: Calls older than 5 minutes are considered abandoned and automatically recovered
494
- 3. **Backend notification**: The backend is notified to process the call's transcript, recording, and analytics
495
- 4. **Automatic cleanup**: The stored state is cleared after recovery or when a call ends naturally
496
-
497
- This recovery mechanism works in **two stages** to ensure complete data integrity:
498
-
499
- - **Stage 1 (App Init)**: Recovers truly abandoned calls (>5 minutes old)
500
- - **Stage 2 (New Call Start)**: Notifies backend of ANY previous call before starting a new one
501
-
502
- This dual approach ensures no call data is ever lost, regardless of user behavior patterns.
503
-
504
- ### Integration
505
-
506
- #### Angular
507
-
508
- Call `recoverAbandonedCall()` during component initialization:
509
-
510
- ```typescript
511
- import { Component, OnInit } from '@angular/core';
512
- import { PlatoApiClient } from 'plato-sdk';
513
-
514
- @Component({
515
- selector: 'app-training',
516
- templateUrl: './training.component.html',
517
- })
518
- export class TrainingComponent implements OnInit {
519
- constructor(private platoClient: PlatoApiClient) {}
520
-
521
- async ngOnInit(): Promise<void> {
522
- // Recover any abandoned calls from previous session
523
- const recovered = await this.platoClient.recoverAbandonedCall();
524
-
525
- if (recovered) {
526
- console.log('Recovered abandoned call from previous session');
527
- // Optional: Show notification to user
528
- this.showNotification('Previous call data recovered and processed');
529
- }
530
-
531
- // Continue with normal initialization
532
- await this.loadSimulations();
533
- }
534
-
535
- showNotification(message: string) {
536
- // Your notification logic here
537
- }
538
- }
539
- ```
540
-
541
- #### React
542
-
543
- Call `recoverAbandonedCall()` in a useEffect hook:
544
-
545
- ```typescript
546
- import { useEffect, useState } from 'react';
547
- import { PlatoApiClient } from 'plato-sdk';
548
-
549
- function TrainingApp() {
550
- const [platoClient] = useState(() => new PlatoApiClient({
551
- baseUrl: 'https://your-api.com',
552
- token: 'your-token',
553
- user: 'your-user',
554
- }));
555
-
556
- useEffect(() => {
557
- const recoverCall = async () => {
558
- try {
559
- const recovered = await platoClient.recoverAbandonedCall();
560
-
561
- if (recovered) {
562
- console.log('Recovered abandoned call');
563
- // Optional: Show toast notification
564
- showToast('Previous call data recovered');
565
- }
566
- } catch (error) {
567
- console.error('Recovery error:', error);
568
- }
569
- };
570
-
571
- recoverCall();
572
- }, [platoClient]);
573
-
574
- return (
575
- // Your app UI
576
- );
577
- }
578
- ```
579
-
580
- ### recoverAbandonedCall()
581
-
582
- Recovers and processes any abandoned calls from previous sessions.
583
-
584
- **Returns:** `Promise<boolean>`
585
-
586
- - `true` if an abandoned call was found and recovered
587
- - `false` if no abandoned call exists or the call is too recent (<5 minutes)
588
-
589
- **Example:**
590
-
591
- ```typescript
592
- // Check if any calls were recovered
593
- const wasRecovered = await client.recoverAbandonedCall();
594
-
595
- if (wasRecovered) {
596
- // An abandoned call was processed
597
- console.log('Successfully recovered abandoned call');
598
- } else {
599
- // No recovery needed
600
- console.log('No abandoned calls to recover');
601
- }
602
- ```
603
-
604
- ### Behavior Details
605
-
606
- #### When Recovery Happens
607
-
608
- **Scenario 1: Abandoned Call (>5 minutes)**
609
-
610
- ```
611
- 10:00:00 - User starts call → State stored
612
- 10:02:00 - User closes browser
613
- 10:08:00 - User returns and opens app
614
- 10:08:01 - recoverAbandonedCall() detects call (>5 min old)
615
- 10:08:01 - Backend notified → Call processed ✓
616
- ```
617
-
618
- **Scenario 2: Recent Call (<5 minutes)**
619
-
620
- ```
621
- 10:00:00 - User starts call → State stored
622
- 10:01:00 - User refreshes page
623
- 10:01:01 - recoverAbandonedCall() checks call (1 min old)
624
- 10:01:01 - Too recent, skip recovery
625
- 10:03:00 - User starts new call
626
- 10:03:00 - startCall() detects previous call
627
- 10:03:00 - Backend notified of previous call → Processed ✓
628
- 10:03:01 - New call starts
629
- ```
630
-
631
- #### Automatic Cleanup
632
-
633
- The SDK automatically clears stored call state when:
634
-
635
- 1. **Call ends naturally**: When `call-end` event fires
636
- 2. **User stops call**: When `stopCall()` is called manually
637
- 3. **New call starts**: Before starting a new call (after notifying backend of previous call)
638
- 4. **After recovery**: After successfully notifying backend of abandoned call
639
-
640
- ### Technical Details
641
-
642
- #### What Gets Stored
643
-
644
- The SDK stores minimal state in `localStorage` under the key `plato_active_call`:
645
-
646
- ```typescript
647
- {
648
- callId: "mongodb-call-id", // MongoDB ID for backend notification
649
- externalCallId: "external-provider-id", // External provider's call ID
650
- simulationId: "simulation-id", // Associated simulation
651
- startedAt: "2025-01-15T10:00:00Z", // ISO 8601 timestamp
652
- version: 1 // Schema version for future compatibility
653
- }
654
- ```
655
-
656
- #### Privacy & Storage
657
-
658
- - **Storage location**: Browser localStorage (persists across sessions)
659
- - **Data size**: ~300 bytes (minimal footprint)
660
- - **Privacy**: Stored locally, never sent to third parties
661
- - **Graceful degradation**: If localStorage is disabled (e.g., private browsing), the SDK continues to work normally but recovery won't be available
662
-
663
- #### Backend Idempotency
664
-
665
- The backend `/api/v1/postcall/call-ended` endpoint is idempotent, meaning:
666
-
667
- - ✅ Safe to call multiple times for the same call
668
- - ✅ No duplicate processing or data corruption
669
- - ✅ Recovery logic can safely notify backend even if uncertain
670
-
671
- This design ensures **data integrity** over potential duplicate notifications.
672
-
673
- ### Edge Cases
674
-
675
- #### Multiple Tabs
676
-
677
- If you have multiple tabs open:
678
-
679
- - Only the most recent call state is stored (single localStorage key)
680
- - Each new call in any tab overwrites previous state
681
- - The most recent call is recovered if needed
682
-
683
- **Impact**: Minimal - calls typically happen one at a time, and the backend handles all notifications properly.
684
-
685
- #### Rapid Actions
686
-
687
- If the user refreshes immediately after starting a call:
688
-
689
- - The call state is stored but not considered abandoned (<5 minutes)
690
- - When the user starts a new call later, the previous call is automatically notified to backend
691
- - No data loss occurs
692
-
693
- #### Browser Closure
694
-
695
- If the browser is force-closed during a call:
696
-
697
- - State persists in localStorage
698
- - On next app launch, recovery detects and processes the call
699
- - Call data is recovered successfully
700
-
701
- #### localStorage Disabled
702
-
703
- If localStorage is disabled (e.g., private browsing mode):
704
-
705
- - All storage operations fail silently
706
- - No errors thrown
707
- - SDK continues to work for normal call flow
708
- - Recovery simply won't be available
709
-
710
- **This is acceptable** because localStorage is enabled in 99%+ of browsers.
711
-
712
- ### Best Practices
713
-
714
- 1. **Always call `recoverAbandonedCall()`** during app initialization to ensure data integrity
715
- 2. **Call it early** in your initialization flow, before other operations
716
- 3. **Handle the return value** to show user notifications when calls are recovered
717
- 4. **Don't block UI** - recovery is fast (<500ms typically) but async
718
- 5. **Trust the system** - the SDK and backend handle all edge cases automatically
719
-
720
- ### Example: Complete Integration
721
-
722
- ```typescript
723
- // Angular Component
724
- @Component({
725
- selector: 'app-root',
726
- templateUrl: './app.component.html',
727
- })
728
- export class AppComponent implements OnInit {
729
- constructor(private platoClient: PlatoApiClient, private toastr: ToastrService) {}
730
-
731
- async ngOnInit(): Promise<void> {
732
- try {
733
- // Step 1: Recover any abandoned calls
734
- const recovered = await this.platoClient.recoverAbandonedCall();
735
-
736
- if (recovered) {
737
- this.toastr.info('Previous call data was recovered and processed');
738
- }
739
-
740
- // Step 2: Continue with normal app initialization
741
- await this.loadUserData();
742
- await this.loadSimulations();
743
- } catch (error) {
744
- console.error('Initialization error:', error);
745
- }
746
- }
747
-
748
- async startCall(simulationId: string): Promise<void> {
749
- try {
750
- // The SDK automatically handles any previous call state
751
- const call = await this.platoClient.startCall(simulationId);
752
-
753
- call.on('call-end', () => {
754
- console.log('Call ended');
755
- // State automatically cleared
756
- });
757
-
758
- call.on('call-details-ready', callDetails => {
759
- console.log('Feedback ready:', callDetails);
760
- });
761
- } catch (error) {
762
- console.error('Call error:', error);
763
- }
764
- }
765
- }
766
- ```
767
-
768
- ### Troubleshooting
769
-
770
- **Q: What if I forget to call `recoverAbandonedCall()`?**
771
-
772
- A: The SDK still protects against data loss through Stage 2 recovery - when you start a new call, it automatically notifies the backend of any previous call. However, it's still recommended to call `recoverAbandonedCall()` for optimal behavior.
773
-
774
- **Q: Can I disable call recovery?**
775
-
776
- A: While you can skip calling `recoverAbandonedCall()`, the Stage 2 recovery (in `startCall()`) always runs to prevent data loss. This is by design to ensure data integrity.
777
-
778
- **Q: How do I know if a call was recovered?**
779
-
780
- A: The `recoverAbandonedCall()` method returns `true` when a call is recovered. Use this to show user notifications or update UI accordingly.
781
-
782
- **Q: What if the backend is down during recovery?**
783
-
784
- A: The recovery attempt is logged and the stored state is cleared to prevent infinite retries. The SDK continues working normally. Recovery failures are graceful and don't break the app.
785
-
786
- ## Event System
787
-
788
- The SDK provides a comprehensive event system for managing voice calls:
789
-
790
- ### Available Events
791
-
792
- - `call-start`: Triggered when a call begins
793
- - `call-end`: Triggered when a call ends
794
- - `speech-start`: Triggered when speech detection starts
795
- - `speech-end`: Triggered when speech detection ends
796
- - `message`: Triggered when a message is received (contains transcript and metadata)
797
- - `volume-level`: Triggered with volume level updates (number)
798
- - `error`: Triggered when an error occurs
799
- - `call-details-ready`: Triggered when post-call processing completes and call details are available (includes full `CallDTO` with transcript, summary, ratings, and evaluation)
800
-
801
- ### Event Usage
802
-
803
- ```typescript
804
- // Subscribe to events
805
- call.on('message', message => {
806
- console.log('Transcript:', message.transcript);
807
- console.log('Type:', message.transcriptType); // 'final' or 'partial'
808
- });
809
-
810
- call.on('volume-level', level => {
811
- console.log('Volume level:', level);
812
- });
813
-
814
- call.on('error', error => {
815
- console.error('Call error:', error);
816
- });
817
-
818
- // Listen for call details after post-call processing
819
- call.on('call-details-ready', callDetails => {
820
- console.log('Post-call feedback ready:', callDetails);
821
- });
822
- ```
823
-
824
- ## Automatic Post-Call Feedback
825
-
826
- The SDK automatically fetches detailed call information after each call ends and completes post-call processing. This includes comprehensive feedback such as transcript, summary, evaluation metrics, strengths, weaknesses, and ratings.
827
-
828
- ### How It Works
829
-
830
- When a call ends, the SDK automatically:
831
-
832
- 1. Triggers the `call-end` event
833
- 2. Processes the call on the backend (post-call analysis)
834
- 3. Fetches complete call details
835
- 4. Emits the `call-details-ready` event with full `CallDTO` data
836
-
837
- This happens automatically—you don't need to manually call `getCallDetails()` after each call.
838
-
839
- ### Event Lifecycle
840
-
841
- ```typescript
842
- const call = await client.startCall(simulationId);
843
-
844
- // 1. Call begins
845
- call.on('call-start', () => {
846
- console.log('Call started');
847
- });
848
-
849
- // 2. Real-time transcript messages during the call
850
- call.on('message', message => {
851
- console.log('Real-time:', message.transcript);
852
- });
853
-
854
- // 3. Call ends
855
- call.on('call-end', () => {
856
- console.log('Call ended - processing feedback...');
857
- });
858
-
859
- // 4. Post-call details are automatically fetched and ready
860
- call.on('call-details-ready', callDetails => {
861
- console.log('Post-call feedback is ready!');
862
-
863
- // Access all call details
864
- console.log('Summary:', callDetails.summary);
865
- console.log('Full Transcript:', callDetails.transcript);
866
- console.log('Call Duration:', callDetails.callDurationMs, 'ms');
867
- console.log('Success:', callDetails.successEvaluation);
868
- console.log('Score:', callDetails.score);
869
-
870
- // Display evaluation metrics
871
- console.log(`${callDetails.metric1}: ${callDetails.metric1Value}`);
872
- console.log(`${callDetails.metric2}: ${callDetails.metric2Value}`);
873
- console.log(`${callDetails.metric3}: ${callDetails.metric3Value}`);
874
-
875
- // Show strengths and areas for improvement
876
- callDetails.strengths?.forEach(strength => {
877
- console.log('✓ Strength:', strength);
878
- });
879
-
880
- callDetails.weaknesses?.forEach(weakness => {
881
- console.log('⚠ Area to improve:', weakness);
882
- });
883
-
884
- // Access recording
885
- if (callDetails.recordingUrl) {
886
- console.log('Recording:', callDetails.recordingUrl);
887
- }
888
- });
889
- ```
890
-
891
- ### Practical Use Cases
892
-
893
- #### 1. Display Post-Call Feedback in UI
894
-
895
- ```typescript
896
- // Angular/React example
897
- async startCall() {
898
- const call = await this.client.startCall(this.simulationId);
899
-
900
- // Automatically update UI when feedback is ready
901
- call.on('call-details-ready', callDetails => {
902
- this.callSummary = callDetails.summary;
903
- this.callScore = callDetails.score;
904
- this.strengths = callDetails.strengths;
905
- this.weaknesses = callDetails.weaknesses;
906
- this.showFeedbackModal = true; // Display feedback to user
907
- });
908
- }
909
- ```
910
-
911
- #### 2. Track Performance Analytics
912
-
913
- ```typescript
914
- call.on('call-details-ready', callDetails => {
915
- // Send analytics to tracking service
916
- analytics.track('call_completed', {
917
- callId: callDetails._id,
918
- duration: callDetails.callDurationMs,
919
- score: callDetails.score,
920
- success: callDetails.successEvaluation,
921
- metrics: {
922
- [callDetails.metric1]: callDetails.metric1Value,
923
- [callDetails.metric2]: callDetails.metric2Value,
924
- [callDetails.metric3]: callDetails.metric3Value,
925
- },
926
- });
927
- });
928
- ```
929
-
930
- #### 3. Store Call History
931
-
932
- ```typescript
933
- call.on('call-details-ready', async callDetails => {
934
- // Save to local storage or database
935
- const callHistory = JSON.parse(localStorage.getItem('call_history') || '[]');
936
- callHistory.push({
937
- id: callDetails._id,
938
- date: callDetails.createdAt,
939
- summary: callDetails.summary,
940
- score: callDetails.score,
941
- });
942
- localStorage.setItem('call_history', JSON.stringify(callHistory));
943
- });
944
- ```
945
-
946
- #### 4. Generate Learning Insights
947
-
948
- ```typescript
949
- call.on('call-details-ready', callDetails => {
950
- // Aggregate insights across multiple calls
951
- if (callDetails.successEvaluation) {
952
- this.successfulCalls++;
953
- this.successStrategies.push(...(callDetails.strengths || []));
954
- } else {
955
- this.areasToImprove.push(...(callDetails.weaknesses || []));
956
- }
957
-
958
- this.updateLearningDashboard();
959
- });
960
- ```
961
-
962
- ### Manual Fetching (Alternative Approach)
963
-
964
- While the SDK automatically fetches call details after each call, you can also manually retrieve them later using the call ID:
965
-
966
- ```typescript
967
- // Get call details at any time
968
- const callDetails = await client.getCallDetails(callId);
969
- ```
970
-
971
- This is useful when:
972
-
973
- - Viewing historical calls
974
- - Refreshing data after updates
975
- - Building a call history view
976
-
977
- ### Error Handling
978
-
979
- If fetching call details fails after a call ends, the error is logged but does not prevent the `call-end` event from completing. The call will still end gracefully.
980
-
981
- ```typescript
982
- call.on('call-end', () => {
983
- console.log('Call ended successfully');
984
- // This will always fire, even if call-details-ready fails
985
- });
986
-
987
- call.on('call-details-ready', callDetails => {
988
- // This may not fire if post-call processing fails
989
- // In that case, you can manually fetch later using getCallDetails()
990
- });
991
- ```
992
-
993
- ### Best Practices
994
-
995
- 1. **Always subscribe to `call-details-ready`** to capture post-call feedback automatically
996
- 2. **Show loading state** between `call-end` and `call-details-ready` events
997
- 3. **Handle missing data gracefully** - some fields may be `null` or `undefined` depending on call status
998
- 4. **Store call IDs** for later retrieval using `getCallDetails()` if needed
999
- 5. **Use the event data** to provide immediate feedback to users rather than making additional API calls
1000
-
1001
- ### Timing Considerations
1002
-
1003
- - `call-end`: Fires immediately when the call stops
1004
- - `call-details-ready`: Fires after backend processing completes (typically 2-5 seconds after call ends)
1005
-
1006
- Plan your UX accordingly—show a loading/processing state between these two events.
1007
-
1008
- ## Data Types
1009
-
1010
- ### CallDTO
1011
-
1012
- Complete call details returned by `call-details-ready` event and `getCallDetails()` method:
1013
-
1014
- ```typescript
1015
- interface CallDTO {
1016
- _id: string; // MongoDB ID of the call
1017
- callId: string; // Vapi call ID
1018
- assistantId: string; // ID of the AI assistant used
1019
- summary?: string; // AI-generated summary of the conversation
1020
- transcript?: string; // Full transcript of the call
1021
- recordingUrl?: string; // URL to the call recording
1022
- rating?: number; // User-provided rating (0-5)
1023
- successEvaluation?: boolean; // Whether the call was successful
1024
- score?: number; // Overall score for the call
1025
- strengths?: string[]; // Array of identified strengths
1026
- weaknesses?: string[]; // Array of areas for improvement
1027
- metric1?: string; // Name of evaluation metric 1
1028
- metric1Value?: number; // Value for metric 1
1029
- metric2?: string; // Name of evaluation metric 2
1030
- metric2Value?: number; // Value for metric 2
1031
- metric3?: string; // Name of evaluation metric 3
1032
- metric3Value?: number; // Value for metric 3
1033
- createdAt: Date; // When the call was created
1034
- endedAt?: Date; // When the call ended
1035
- callDurationMs?: number; // Duration in milliseconds
1036
- // Additional fields may be present depending on call status
1037
- }
1038
- ```
1039
-
1040
- ### CreateSimulationDto
1041
-
1042
- Configuration for creating a simulation:
1043
-
1044
- ```typescript
1045
- interface CreateSimulationDto {
1046
- persona: CharacterCreateDto;
1047
- product: ProductConfig;
1048
- presentation?: string;
1049
- scenario: string;
1050
- objectives?: string;
1051
- anticipatedObjections?: string;
1052
- trainingConfiguration: TrainingConfigurationDto;
1053
- imageId: string;
1054
- avatarLanguage: AvatarLanguage;
1055
- }
1056
- ```
1057
-
1058
- ### CharacterCreateDto
1059
-
1060
- AI persona configuration:
1061
-
1062
- ```typescript
1063
- interface CharacterCreateDto {
1064
- name: string;
1065
- professionalProfile: ProfessionalProfileDto;
1066
- segment: SegmentType;
1067
- personalityAndBehaviour: PersonalityAndBehaviourDto;
1068
- context: ContextDto;
1069
- assistantGender?: AssistantVoiceGender;
1070
- }
1071
- ```
1072
-
1073
- ### SimulationDetailsDto
1074
-
1075
- Detailed simulation information returned by `getSimulationDetails()`:
1076
-
1077
- ```typescript
1078
- interface SimulationDetailsDto {
1079
- simulationId: string;
1080
- phase: CreationPhase;
1081
- assistantId: string;
1082
- configuration?: CreateSimulationDto;
1083
- createdAt: Date;
1084
- updatedAt: Date;
1085
- }
1086
- ```
1087
-
1088
- ### CreationPhase
1089
-
1090
- Enum representing the simulation creation phases:
1091
-
1092
- ```typescript
1093
- enum CreationPhase {
1094
- STARTING = 'STARTING',
1095
- CORE = 'CORE',
1096
- BOUNDARIES = 'BOUNDARIES',
1097
- SPEECH_AND_THOUGHT = 'SPEECH_AND_THOUGHT',
1098
- CONVERSATION_EVOLUTION = 'CONVERSATION_EVOLUTION',
1099
- MEMORY = 'MEMORY',
1100
- FINISHED = 'FINISHED',
1101
- ERROR = 'ERROR',
1102
- }
1103
- ```
1104
-
1105
- ### RecommendationsResponseDto
1106
-
1107
- Response object from `getRecommendations()`:
1108
-
1109
- ```typescript
1110
- interface RecommendationsResponseDto {
1111
- recommendations: RecommendationItemDto[];
1112
- strengths: PerformancePatternDto[];
1113
- improvementAreas: ImprovementAreaDto[];
1114
- summary: string;
1115
- callsAnalyzed: number;
1116
- generatedAt: Date;
1117
- }
1118
-
1119
- interface RecommendationItemDto {
1120
- title: string;
1121
- description: string;
1122
- priority: 'high' | 'medium' | 'low';
1123
- }
1124
-
1125
- interface PerformancePatternDto {
1126
- strength: string;
1127
- frequency: number;
1128
- }
1129
-
1130
- interface ImprovementAreaDto {
1131
- area: string;
1132
- frequency: number;
1133
- }
1134
- ```
1135
-
1136
- ### PdfSlidesDto
1137
-
1138
- Simplified data structure for PDF slide records (used in lists):
1139
-
1140
- ```typescript
1141
- interface PdfSlidesDto {
1142
- _id: string;
1143
- originalFilename: string;
1144
- totalSlides?: number;
1145
- lessonOverview?: string;
1146
- createdAt: Date;
1147
- updatedAt: Date;
1148
- }
1149
- ```
1150
-
1151
- ### PdfSlideDto
1152
-
1153
- Detailed data structure for a single PDF slide analysis:
1154
-
1155
- ```typescript
1156
- interface PdfSlideDto {
1157
- _id: string;
1158
- originalFilename: string;
1159
- totalSlides?: number;
1160
- lessonOverview?: string;
1161
- slideAnalysis?: Array<{
1162
- slideNumber: number;
1163
- title: string;
1164
- textExtraction: string;
1165
- }>;
1166
- createdAt: Date;
1167
- updatedAt: Date;
1168
- }
1169
- ```
1170
-
1171
- ### PdfSlidesAnalysisQueryDto
1172
-
1173
- Query parameters for retrieving slide analysis records:
1174
-
1175
- ```typescript
1176
- interface PdfSlidesAnalysisQueryDto {
1177
- limit?: 5 | 10 | 25;
1178
- page?: number;
1179
- sort?: 'asc' | 'desc';
1180
- sortBy?: 'createdAt' | 'originalFilename' | 'totalSlides';
1181
- }
1182
- ```
1183
-
1184
- ### AssistantImageDto
1185
-
1186
- Data structure for assistant images:
1187
-
1188
- ```typescript
1189
- interface AssistantImageDto {
1190
- _id: string;
1191
- imageUrl: string;
1192
- }
1193
- ```
1194
-
1195
- ### AvatarLanguage
1196
-
1197
- Enum representing available avatar languages:
1198
-
1199
- ```typescript
1200
- enum AvatarLanguage {
1201
- English = 'en',
1202
- German = 'de',
1203
- Spanish = 'es',
1204
- Italian = 'it',
1205
- French = 'fr',
1206
- }
1207
- ```
1208
-
1209
- ## Error Handling
1210
-
1211
- The SDK throws errors for invalid configurations and API failures:
1212
-
1213
- ```typescript
1214
- try {
1215
- const client = new PlatoApiClient({
1216
- baseUrl: 'https://api.plato.com',
1217
- token: 'your-token',
1218
- user: 'your-user',
1219
- });
1220
-
1221
- const simulation = await client.createSimulation(simulationConfig);
1222
- const call = await client.startCall(simulation.simulationId);
1223
- } catch (error) {
1224
- console.error('Error:', error.message);
1225
- }
1226
- ```
1227
-
1228
- ## Support
1229
-
1230
- For support and questions, please contact the development team.