@ctchealth/plato-sdk 0.0.15 → 0.0.16

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.
Files changed (2) hide show
  1. package/README.md +1334 -0
  2. package/package.json +2 -2
package/README.md ADDED
@@ -0,0 +1,1334 @@
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>` — The MongoDB ID of the created PDF record, which can be used to track the analysis status.
280
+
281
+ **Limitations:**
282
+
283
+ - **Latin-only file names:** The PDF file name must contain only Latin characters. Non-latin characters in the file name are not supported.
284
+ - **Maximum 100 pages:** PDF files cannot exceed 100 pages.
285
+ - **No duplicate content:** Uploading a PDF with identical content to an already uploaded file is not allowed. Duplicates are detected based on file content, not file name.
286
+
287
+ **Example:**
288
+
289
+ ```typescript
290
+ // Upload a PDF file from an input element
291
+ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
292
+ const file = fileInput.files?.[0];
293
+
294
+ if (file) {
295
+ const pdfId = await client.uploadPdfSlides(file);
296
+ console.log('PDF upload initiated, ID:', pdfId);
297
+
298
+ // Now you can immediately check the status using the returned ID
299
+ const status = await client.checkPdfStatus(pdfId);
300
+ console.log('Initial status:', status);
301
+ }
302
+ ```
303
+
304
+ ##### getSlidesAnalysis(queryParams: PdfSlidesAnalysisQueryDto)
305
+
306
+ Retrieves a paginated and sorted list of PDF slide analysis records.
307
+
308
+ **Parameters:**
309
+
310
+ - `queryParams` (PdfSlidesAnalysisQueryDto):
311
+ - `limit` (optional): Number of records per page
312
+ - `page` (optional): Page number
313
+ - `sort` (optional): Sort order (`'asc'` or `'desc'`)
314
+ - `sortBy` (optional): Field to sort by (`'createdAt'`, `'originalFilename'`, or `'totalSlides'`)
315
+
316
+ **Returns:** `Promise<PdfSlidesDto[]>`
317
+
318
+ **Example:**
319
+
320
+ ```typescript
321
+ const analysisList = await client.getSlidesAnalysis({
322
+ limit: 10,
323
+ page: 0,
324
+ sort: 'desc',
325
+ sortBy: 'createdAt',
326
+ });
327
+ ```
328
+
329
+ ##### getSlideAnalysis(id: string)
330
+
331
+ Retrieves the detailed analysis data for a specific PDF slide record, including the overview and individual slide analysis.
332
+
333
+ **Parameters:**
334
+
335
+ - `id` (string): The unique ID of the PDF slide record
336
+
337
+ **Returns:** `Promise<PdfSlideDto>`
338
+
339
+ **Example:**
340
+
341
+ ```typescript
342
+ const details = await client.getSlideAnalysis('pdf-slide-id');
343
+ console.log('Lesson Overview:', details.lessonOverview);
344
+ ```
345
+
346
+ ##### deleteSlideAnalysis(id: string)
347
+
348
+ Deletes a PDF slide analysis record from the database and removes the corresponding file from S3 storage.
349
+
350
+ **Parameters:**
351
+
352
+ - `id` (string): The unique ID of the PDF slide record to delete
353
+
354
+ **Returns:** `Promise<void>`
355
+
356
+ **Example:**
357
+
358
+ ```typescript
359
+ await client.deleteSlideAnalysis('pdf-slide-id');
360
+ console.log('Analysis deleted successfully');
361
+ ```
362
+
363
+ ##### checkPdfStatus(id: string)
364
+
365
+ Checks the current processing status of a PDF slide analysis. Use this to monitor the progress of PDF analysis workflows.
366
+
367
+ **Parameters:**
368
+
369
+ - `id` (string): The unique ID of the PDF slide record
370
+
371
+ **Returns:** `Promise<{ status: PdfSlidesStatus }>` — An object containing the current status
372
+
373
+ **Available Status Values:**
374
+
375
+ - `started` - PDF uploaded and record created
376
+ - `processing` - Receiving batches of analyzed slides
377
+ - `overview` - All slides analyzed, generating lesson overview
378
+ - `completed` - Analysis complete and ready to view
379
+ - `failed` - Analysis failed (currently not implemented)
380
+
381
+ **Example:**
382
+
383
+ ```typescript
384
+ // Check PDF analysis status
385
+ const { status } = await client.checkPdfStatus('pdf-slide-id');
386
+
387
+ console.log('Current status:', status);
388
+ ```
389
+
390
+ **Typical Workflow:**
391
+
392
+ ```typescript
393
+ // 1. Upload PDF and get the ID immediately
394
+ const pdfId = await client.uploadPdfSlides(file);
395
+ console.log('PDF uploaded with ID:', pdfId);
396
+
397
+ // 2. Poll status until complete
398
+ const checkStatus = async () => {
399
+ const { status } = await client.checkPdfStatus(pdfId);
400
+
401
+ switch (status) {
402
+ case 'pending':
403
+ console.log('Waiting for upload confirmation...');
404
+ break;
405
+ case 'started':
406
+ console.log('Upload confirmed, starting analysis...');
407
+ break;
408
+ case 'processing':
409
+ console.log('Analyzing slides...');
410
+ break;
411
+ case 'overview':
412
+ console.log('Generating lesson overview...');
413
+ break;
414
+ case 'completed':
415
+ console.log('Analysis complete!');
416
+ // Now fetch the full analysis
417
+ const analysis = await client.getSlideAnalysis(pdfId);
418
+ console.log('Lesson overview:', analysis.lessonOverview);
419
+ return; // Stop polling
420
+ case 'failed':
421
+ console.log('Analysis failed');
422
+ return; // Stop polling
423
+ }
424
+
425
+ // Check again in 3 seconds
426
+ setTimeout(checkStatus, 3000);
427
+ };
428
+
429
+ checkStatus();
430
+ ```
431
+
432
+ ##### getAssistantImages()
433
+
434
+ Retrieves all available assistant images that can be used when creating a simulation.
435
+
436
+ **Returns:** `Promise<AssistantImageDto[]>` — An array of assistant image objects, each containing:
437
+
438
+ - `_id`: Unique identifier for the image
439
+ - `imageUrl`: URL of the assistant image
440
+
441
+ **Example:**
442
+
443
+ ```typescript
444
+ // Get all available assistant images
445
+ const images = await client.getAssistantImages();
446
+ ```
447
+
448
+ ##### getRecommendations()
449
+
450
+ 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.
451
+
452
+ **Returns:** `Promise<RecommendationsResponseDto>` — An object containing:
453
+
454
+ - `recommendations`: Array of recommendation objects, each with:
455
+ - `title`: Brief title of the recommendation
456
+ - `description`: Detailed, actionable description
457
+ - `priority`: Priority level (`'high'`, `'medium'`, or `'low'`)
458
+ - `strengths`: Array of identified strengths, each with:
459
+ - `strength`: Description of the strength
460
+ - `frequency`: Number of calls where this strength appeared
461
+ - `improvementAreas`: Array of areas needing improvement, each with:
462
+ - `area`: Description of the improvement area
463
+ - `frequency`: Number of calls where this weakness appeared
464
+ - `summary`: A 2-3 sentence overall summary of performance trends
465
+ - `callsAnalyzed`: Number of calls that were analyzed
466
+ - `generatedAt`: Timestamp when the recommendations were generated
467
+
468
+ **Example:**
469
+
470
+ ```typescript
471
+ // Get personalized recommendations based on call history
472
+ const recommendations = await client.getRecommendations();
473
+
474
+ console.log(`Analyzed ${recommendations.callsAnalyzed} calls`);
475
+ console.log('Summary:', recommendations.summary);
476
+
477
+ // Display high-priority recommendations
478
+ recommendations.recommendations
479
+ .filter(rec => rec.priority === 'high')
480
+ .forEach(rec => {
481
+ console.log(`[HIGH] ${rec.title}: ${rec.description}`);
482
+ });
483
+
484
+ // Show recurring strengths
485
+ recommendations.strengths.forEach(s => {
486
+ console.log(`Strength (${s.frequency} calls): ${s.strength}`);
487
+ });
488
+
489
+ // Show areas for improvement
490
+ recommendations.improvementAreas.forEach(area => {
491
+ console.log(`Needs work (${area.frequency} calls): ${area.area}`);
492
+ });
493
+ ```
494
+
495
+ **Note:** This method requires the user to have at least one completed call. If no calls are found, a `BadRequestException` will be thrown.
496
+
497
+ ## Checking Simulation Status
498
+
499
+ 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.
500
+
501
+ ```typescript
502
+ const status = await client.checkSimulationStatus(simulation.simulationId);
503
+ console.log('Current phase:', status.phase); // e.g., 'FINISHED', 'ERROR', etc.
504
+ ```
505
+
506
+ - **Returns:** `{ phase: CreationPhase }` — The current phase of the simulation creation process.
507
+ - **Typical usage:** Poll this method until the phase is `FINISHED` or `ERROR` before starting a call.
508
+
509
+ ## Simulation Persistence
510
+
511
+ Simulations are persisted server-side and can be recovered after page reloads. Store the simulation ID client-side (e.g., localStorage) for quick recovery.
512
+
513
+ ### getSimulationDetails(simulationId: string)
514
+
515
+ Retrieves detailed information about a simulation, including its original configuration.
516
+
517
+ **Returns:** `Promise<SimulationDetailsDto>` containing:
518
+
519
+ - `simulationId`: MongoDB ID
520
+ - `phase`: Current creation phase
521
+ - `assistantId`: The assistant ID (available after creation)
522
+ - `configuration`: Original `CreateSimulationDto`
523
+ - `createdAt`, `updatedAt`: Timestamps
524
+
525
+ **Example:**
526
+
527
+ ```typescript
528
+ // Store simulation ID after creation
529
+ const simulation = await client.createSimulation(config);
530
+ localStorage.setItem('plato_simulation_id', simulation.simulationId);
531
+
532
+ // Recover simulation on page reload
533
+ const simulationId = localStorage.getItem('plato_simulation_id');
534
+ if (simulationId) {
535
+ const details = await client.getSimulationDetails(simulationId);
536
+
537
+ if (details.phase !== CreationPhase.ERROR) {
538
+ // Resume polling if still in progress
539
+ if (details.phase !== CreationPhase.FINISHED) {
540
+ startPolling(details.simulationId);
541
+ }
542
+ } else {
543
+ localStorage.removeItem('plato_simulation_id');
544
+ }
545
+ }
546
+ ```
547
+
548
+ ### getUserSimulations()
549
+
550
+ Retrieves all simulations for the authenticated user. Useful when the simulation ID is not stored locally.
551
+
552
+ **Returns:** `Promise<Array<{ simulationId: string; phase: CreationPhase }>>`
553
+
554
+ **Example:**
555
+
556
+ ```typescript
557
+ const simulations = await client.getUserSimulations();
558
+ const inProgress = simulations.find(
559
+ sim => sim.phase !== CreationPhase.FINISHED && sim.phase !== CreationPhase.ERROR
560
+ );
561
+ ```
562
+
563
+ ## Call Recovery
564
+
565
+ 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.
566
+
567
+ ### How It Works
568
+
569
+ When you start a call, the SDK stores minimal call state in the browser's localStorage. If the page is refreshed:
570
+
571
+ 1. **On app initialization**: The `recoverAbandonedCall()` method checks for any stored call state
572
+ 2. **Age-based recovery**: Calls older than 5 minutes are considered abandoned and automatically recovered
573
+ 3. **Backend notification**: The backend is notified to process the call's transcript, recording, and analytics
574
+ 4. **Automatic cleanup**: The stored state is cleared after recovery or when a call ends naturally
575
+
576
+ This recovery mechanism works in **two stages** to ensure complete data integrity:
577
+
578
+ - **Stage 1 (App Init)**: Recovers truly abandoned calls (>5 minutes old)
579
+ - **Stage 2 (New Call Start)**: Notifies backend of ANY previous call before starting a new one
580
+
581
+ This dual approach ensures no call data is ever lost, regardless of user behavior patterns.
582
+
583
+ ### Integration
584
+
585
+ #### Angular
586
+
587
+ Call `recoverAbandonedCall()` during component initialization:
588
+
589
+ ```typescript
590
+ import { Component, OnInit } from '@angular/core';
591
+ import { PlatoApiClient } from 'plato-sdk';
592
+
593
+ @Component({
594
+ selector: 'app-training',
595
+ templateUrl: './training.component.html',
596
+ })
597
+ export class TrainingComponent implements OnInit {
598
+ constructor(private platoClient: PlatoApiClient) {}
599
+
600
+ async ngOnInit(): Promise<void> {
601
+ // Recover any abandoned calls from previous session
602
+ const recovered = await this.platoClient.recoverAbandonedCall();
603
+
604
+ if (recovered) {
605
+ console.log('Recovered abandoned call from previous session');
606
+ // Optional: Show notification to user
607
+ this.showNotification('Previous call data recovered and processed');
608
+ }
609
+
610
+ // Continue with normal initialization
611
+ await this.loadSimulations();
612
+ }
613
+
614
+ showNotification(message: string) {
615
+ // Your notification logic here
616
+ }
617
+ }
618
+ ```
619
+
620
+ #### React
621
+
622
+ Call `recoverAbandonedCall()` in a useEffect hook:
623
+
624
+ ```typescript
625
+ import { useEffect, useState } from 'react';
626
+ import { PlatoApiClient } from 'plato-sdk';
627
+
628
+ function TrainingApp() {
629
+ const [platoClient] = useState(() => new PlatoApiClient({
630
+ baseUrl: 'https://your-api.com',
631
+ token: 'your-token',
632
+ user: 'your-user',
633
+ }));
634
+
635
+ useEffect(() => {
636
+ const recoverCall = async () => {
637
+ try {
638
+ const recovered = await platoClient.recoverAbandonedCall();
639
+
640
+ if (recovered) {
641
+ console.log('Recovered abandoned call');
642
+ // Optional: Show toast notification
643
+ showToast('Previous call data recovered');
644
+ }
645
+ } catch (error) {
646
+ console.error('Recovery error:', error);
647
+ }
648
+ };
649
+
650
+ recoverCall();
651
+ }, [platoClient]);
652
+
653
+ return (
654
+ // Your app UI
655
+ );
656
+ }
657
+ ```
658
+
659
+ ### recoverAbandonedCall()
660
+
661
+ Recovers and processes any abandoned calls from previous sessions.
662
+
663
+ **Returns:** `Promise<boolean>`
664
+
665
+ - `true` if an abandoned call was found and recovered
666
+ - `false` if no abandoned call exists or the call is too recent (<5 minutes)
667
+
668
+ **Example:**
669
+
670
+ ```typescript
671
+ // Check if any calls were recovered
672
+ const wasRecovered = await client.recoverAbandonedCall();
673
+
674
+ if (wasRecovered) {
675
+ // An abandoned call was processed
676
+ console.log('Successfully recovered abandoned call');
677
+ } else {
678
+ // No recovery needed
679
+ console.log('No abandoned calls to recover');
680
+ }
681
+ ```
682
+
683
+ ### Behavior Details
684
+
685
+ #### When Recovery Happens
686
+
687
+ **Scenario 1: Abandoned Call (>5 minutes)**
688
+
689
+ ```
690
+ 10:00:00 - User starts call → State stored
691
+ 10:02:00 - User closes browser
692
+ 10:08:00 - User returns and opens app
693
+ 10:08:01 - recoverAbandonedCall() detects call (>5 min old)
694
+ 10:08:01 - Backend notified → Call processed ✓
695
+ ```
696
+
697
+ **Scenario 2: Recent Call (<5 minutes)**
698
+
699
+ ```
700
+ 10:00:00 - User starts call → State stored
701
+ 10:01:00 - User refreshes page
702
+ 10:01:01 - recoverAbandonedCall() checks call (1 min old)
703
+ 10:01:01 - Too recent, skip recovery
704
+ 10:03:00 - User starts new call
705
+ 10:03:00 - startCall() detects previous call
706
+ 10:03:00 - Backend notified of previous call → Processed ✓
707
+ 10:03:01 - New call starts
708
+ ```
709
+
710
+ #### Automatic Cleanup
711
+
712
+ The SDK automatically clears stored call state when:
713
+
714
+ 1. **Call ends naturally**: When `call-end` event fires
715
+ 2. **User stops call**: When `stopCall()` is called manually
716
+ 3. **New call starts**: Before starting a new call (after notifying backend of previous call)
717
+ 4. **After recovery**: After successfully notifying backend of abandoned call
718
+
719
+ ### Technical Details
720
+
721
+ #### What Gets Stored
722
+
723
+ The SDK stores minimal state in `localStorage` under the key `plato_active_call`:
724
+
725
+ ```typescript
726
+ {
727
+ callId: "mongodb-call-id", // MongoDB ID for backend notification
728
+ externalCallId: "external-provider-id", // External provider's call ID
729
+ simulationId: "simulation-id", // Associated simulation
730
+ startedAt: "2025-01-15T10:00:00Z", // ISO 8601 timestamp
731
+ version: 1 // Schema version for future compatibility
732
+ }
733
+ ```
734
+
735
+ #### Privacy & Storage
736
+
737
+ - **Storage location**: Browser localStorage (persists across sessions)
738
+ - **Data size**: ~300 bytes (minimal footprint)
739
+ - **Privacy**: Stored locally, never sent to third parties
740
+ - **Graceful degradation**: If localStorage is disabled (e.g., private browsing), the SDK continues to work normally but recovery won't be available
741
+
742
+ #### Backend Idempotency
743
+
744
+ The backend `/api/v1/postcall/call-ended` endpoint is idempotent, meaning:
745
+
746
+ - ✅ Safe to call multiple times for the same call
747
+ - ✅ No duplicate processing or data corruption
748
+ - ✅ Recovery logic can safely notify backend even if uncertain
749
+
750
+ This design ensures **data integrity** over potential duplicate notifications.
751
+
752
+ ### Edge Cases
753
+
754
+ #### Multiple Tabs
755
+
756
+ If you have multiple tabs open:
757
+
758
+ - Only the most recent call state is stored (single localStorage key)
759
+ - Each new call in any tab overwrites previous state
760
+ - The most recent call is recovered if needed
761
+
762
+ **Impact**: Minimal - calls typically happen one at a time, and the backend handles all notifications properly.
763
+
764
+ #### Rapid Actions
765
+
766
+ If the user refreshes immediately after starting a call:
767
+
768
+ - The call state is stored but not considered abandoned (<5 minutes)
769
+ - When the user starts a new call later, the previous call is automatically notified to backend
770
+ - No data loss occurs
771
+
772
+ #### Browser Closure
773
+
774
+ If the browser is force-closed during a call:
775
+
776
+ - State persists in localStorage
777
+ - On next app launch, recovery detects and processes the call
778
+ - Call data is recovered successfully
779
+
780
+ #### localStorage Disabled
781
+
782
+ If localStorage is disabled (e.g., private browsing mode):
783
+
784
+ - All storage operations fail silently
785
+ - No errors thrown
786
+ - SDK continues to work for normal call flow
787
+ - Recovery simply won't be available
788
+
789
+ **This is acceptable** because localStorage is enabled in 99%+ of browsers.
790
+
791
+ ### Best Practices
792
+
793
+ 1. **Always call `recoverAbandonedCall()`** during app initialization to ensure data integrity
794
+ 2. **Call it early** in your initialization flow, before other operations
795
+ 3. **Handle the return value** to show user notifications when calls are recovered
796
+ 4. **Don't block UI** - recovery is fast (<500ms typically) but async
797
+ 5. **Trust the system** - the SDK and backend handle all edge cases automatically
798
+
799
+ ### Example: Complete Integration
800
+
801
+ ```typescript
802
+ // Angular Component
803
+ @Component({
804
+ selector: 'app-root',
805
+ templateUrl: './app.component.html',
806
+ })
807
+ export class AppComponent implements OnInit {
808
+ constructor(private platoClient: PlatoApiClient, private toastr: ToastrService) {}
809
+
810
+ async ngOnInit(): Promise<void> {
811
+ try {
812
+ // Step 1: Recover any abandoned calls
813
+ const recovered = await this.platoClient.recoverAbandonedCall();
814
+
815
+ if (recovered) {
816
+ this.toastr.info('Previous call data was recovered and processed');
817
+ }
818
+
819
+ // Step 2: Continue with normal app initialization
820
+ await this.loadUserData();
821
+ await this.loadSimulations();
822
+ } catch (error) {
823
+ console.error('Initialization error:', error);
824
+ }
825
+ }
826
+
827
+ async startCall(simulationId: string): Promise<void> {
828
+ try {
829
+ // The SDK automatically handles any previous call state
830
+ const call = await this.platoClient.startCall(simulationId);
831
+
832
+ call.on('call-end', () => {
833
+ console.log('Call ended');
834
+ // State automatically cleared
835
+ });
836
+
837
+ call.on('call-details-ready', callDetails => {
838
+ console.log('Feedback ready:', callDetails);
839
+ });
840
+ } catch (error) {
841
+ console.error('Call error:', error);
842
+ }
843
+ }
844
+ }
845
+ ```
846
+
847
+ ### Troubleshooting
848
+
849
+ **Q: What if I forget to call `recoverAbandonedCall()`?**
850
+
851
+ 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.
852
+
853
+ **Q: Can I disable call recovery?**
854
+
855
+ 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.
856
+
857
+ **Q: How do I know if a call was recovered?**
858
+
859
+ A: The `recoverAbandonedCall()` method returns `true` when a call is recovered. Use this to show user notifications or update UI accordingly.
860
+
861
+ **Q: What if the backend is down during recovery?**
862
+
863
+ 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.
864
+
865
+ ## Event System
866
+
867
+ The SDK provides a comprehensive event system for managing voice calls:
868
+
869
+ ### Available Events
870
+
871
+ - `call-start`: Triggered when a call begins
872
+ - `call-end`: Triggered when a call ends
873
+ - `speech-start`: Triggered when speech detection starts
874
+ - `speech-end`: Triggered when speech detection ends
875
+ - `message`: Triggered when a message is received (contains transcript and metadata)
876
+ - `volume-level`: Triggered with volume level updates (number)
877
+ - `error`: Triggered when an error occurs
878
+ - `call-details-ready`: Triggered when post-call processing completes and call details are available (includes full `CallDTO` with transcript, summary, ratings, and evaluation)
879
+
880
+ ### Event Usage
881
+
882
+ ```typescript
883
+ // Subscribe to events
884
+ call.on('message', message => {
885
+ console.log('Transcript:', message.transcript);
886
+ console.log('Type:', message.transcriptType); // 'final' or 'partial'
887
+ });
888
+
889
+ call.on('volume-level', level => {
890
+ console.log('Volume level:', level);
891
+ });
892
+
893
+ call.on('error', error => {
894
+ console.error('Call error:', error);
895
+ });
896
+
897
+ // Listen for call details after post-call processing
898
+ call.on('call-details-ready', callDetails => {
899
+ console.log('Post-call feedback ready:', callDetails);
900
+ });
901
+ ```
902
+
903
+ ## Automatic Post-Call Feedback
904
+
905
+ 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.
906
+
907
+ ### How It Works
908
+
909
+ When a call ends, the SDK automatically:
910
+
911
+ 1. Triggers the `call-end` event
912
+ 2. Processes the call on the backend (post-call analysis)
913
+ 3. Fetches complete call details
914
+ 4. Emits the `call-details-ready` event with full `CallDTO` data
915
+
916
+ This happens automatically—you don't need to manually call `getCallDetails()` after each call.
917
+
918
+ ### Event Lifecycle
919
+
920
+ ```typescript
921
+ const call = await client.startCall(simulationId);
922
+
923
+ // 1. Call begins
924
+ call.on('call-start', () => {
925
+ console.log('Call started');
926
+ });
927
+
928
+ // 2. Real-time transcript messages during the call
929
+ call.on('message', message => {
930
+ console.log('Real-time:', message.transcript);
931
+ });
932
+
933
+ // 3. Call ends
934
+ call.on('call-end', () => {
935
+ console.log('Call ended - processing feedback...');
936
+ });
937
+
938
+ // 4. Post-call details are automatically fetched and ready
939
+ call.on('call-details-ready', callDetails => {
940
+ console.log('Post-call feedback is ready!');
941
+
942
+ // Access all call details
943
+ console.log('Summary:', callDetails.summary);
944
+ console.log('Full Transcript:', callDetails.transcript);
945
+ console.log('Call Duration:', callDetails.callDurationMs, 'ms');
946
+ console.log('Success:', callDetails.successEvaluation);
947
+ console.log('Score:', callDetails.score);
948
+
949
+ // Display evaluation metrics
950
+ console.log(`${callDetails.metric1}: ${callDetails.metric1Value}`);
951
+ console.log(`${callDetails.metric2}: ${callDetails.metric2Value}`);
952
+ console.log(`${callDetails.metric3}: ${callDetails.metric3Value}`);
953
+
954
+ // Show strengths and areas for improvement
955
+ callDetails.strengths?.forEach(strength => {
956
+ console.log('✓ Strength:', strength);
957
+ });
958
+
959
+ callDetails.weaknesses?.forEach(weakness => {
960
+ console.log('⚠ Area to improve:', weakness);
961
+ });
962
+
963
+ // Access recording
964
+ if (callDetails.recordingUrl) {
965
+ console.log('Recording:', callDetails.recordingUrl);
966
+ }
967
+ });
968
+ ```
969
+
970
+ ### Practical Use Cases
971
+
972
+ #### 1. Display Post-Call Feedback in UI
973
+
974
+ ```typescript
975
+ // Angular/React example
976
+ async startCall() {
977
+ const call = await this.client.startCall(this.simulationId);
978
+
979
+ // Automatically update UI when feedback is ready
980
+ call.on('call-details-ready', callDetails => {
981
+ this.callSummary = callDetails.summary;
982
+ this.callScore = callDetails.score;
983
+ this.strengths = callDetails.strengths;
984
+ this.weaknesses = callDetails.weaknesses;
985
+ this.showFeedbackModal = true; // Display feedback to user
986
+ });
987
+ }
988
+ ```
989
+
990
+ #### 2. Track Performance Analytics
991
+
992
+ ```typescript
993
+ call.on('call-details-ready', callDetails => {
994
+ // Send analytics to tracking service
995
+ analytics.track('call_completed', {
996
+ callId: callDetails._id,
997
+ duration: callDetails.callDurationMs,
998
+ score: callDetails.score,
999
+ success: callDetails.successEvaluation,
1000
+ metrics: {
1001
+ [callDetails.metric1]: callDetails.metric1Value,
1002
+ [callDetails.metric2]: callDetails.metric2Value,
1003
+ [callDetails.metric3]: callDetails.metric3Value,
1004
+ },
1005
+ });
1006
+ });
1007
+ ```
1008
+
1009
+ #### 3. Store Call History
1010
+
1011
+ ```typescript
1012
+ call.on('call-details-ready', async callDetails => {
1013
+ // Save to local storage or database
1014
+ const callHistory = JSON.parse(localStorage.getItem('call_history') || '[]');
1015
+ callHistory.push({
1016
+ id: callDetails._id,
1017
+ date: callDetails.createdAt,
1018
+ summary: callDetails.summary,
1019
+ score: callDetails.score,
1020
+ });
1021
+ localStorage.setItem('call_history', JSON.stringify(callHistory));
1022
+ });
1023
+ ```
1024
+
1025
+ #### 4. Generate Learning Insights
1026
+
1027
+ ```typescript
1028
+ call.on('call-details-ready', callDetails => {
1029
+ // Aggregate insights across multiple calls
1030
+ if (callDetails.successEvaluation) {
1031
+ this.successfulCalls++;
1032
+ this.successStrategies.push(...(callDetails.strengths || []));
1033
+ } else {
1034
+ this.areasToImprove.push(...(callDetails.weaknesses || []));
1035
+ }
1036
+
1037
+ this.updateLearningDashboard();
1038
+ });
1039
+ ```
1040
+
1041
+ ### Manual Fetching (Alternative Approach)
1042
+
1043
+ While the SDK automatically fetches call details after each call, you can also manually retrieve them later using the call ID:
1044
+
1045
+ ```typescript
1046
+ // Get call details at any time
1047
+ const callDetails = await client.getCallDetails(callId);
1048
+ ```
1049
+
1050
+ This is useful when:
1051
+
1052
+ - Viewing historical calls
1053
+ - Refreshing data after updates
1054
+ - Building a call history view
1055
+
1056
+ ### Error Handling
1057
+
1058
+ 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.
1059
+
1060
+ ```typescript
1061
+ call.on('call-end', () => {
1062
+ console.log('Call ended successfully');
1063
+ // This will always fire, even if call-details-ready fails
1064
+ });
1065
+
1066
+ call.on('call-details-ready', callDetails => {
1067
+ // This may not fire if post-call processing fails
1068
+ // In that case, you can manually fetch later using getCallDetails()
1069
+ });
1070
+ ```
1071
+
1072
+ ### Best Practices
1073
+
1074
+ 1. **Always subscribe to `call-details-ready`** to capture post-call feedback automatically
1075
+ 2. **Show loading state** between `call-end` and `call-details-ready` events
1076
+ 3. **Handle missing data gracefully** - some fields may be `null` or `undefined` depending on call status
1077
+ 4. **Store call IDs** for later retrieval using `getCallDetails()` if needed
1078
+ 5. **Use the event data** to provide immediate feedback to users rather than making additional API calls
1079
+
1080
+ ### Timing Considerations
1081
+
1082
+ - `call-end`: Fires immediately when the call stops
1083
+ - `call-details-ready`: Fires after backend processing completes (typically 2-5 seconds after call ends)
1084
+
1085
+ Plan your UX accordingly—show a loading/processing state between these two events.
1086
+
1087
+ ## Data Types
1088
+
1089
+ ### CallDTO
1090
+
1091
+ Complete call details returned by `call-details-ready` event and `getCallDetails()` method:
1092
+
1093
+ ```typescript
1094
+ interface CallDTO {
1095
+ _id: string; // MongoDB ID of the call
1096
+ callId: string; // Vapi call ID
1097
+ assistantId: string; // ID of the AI assistant used
1098
+ summary?: string; // AI-generated summary of the conversation
1099
+ transcript?: string; // Full transcript of the call
1100
+ recordingUrl?: string; // URL to the call recording
1101
+ rating?: number; // User-provided rating (0-5)
1102
+ successEvaluation?: boolean; // Whether the call was successful
1103
+ score?: number; // Overall score for the call
1104
+ strengths?: string[]; // Array of identified strengths
1105
+ weaknesses?: string[]; // Array of areas for improvement
1106
+ metric1?: string; // Name of evaluation metric 1
1107
+ metric1Value?: number; // Value for metric 1
1108
+ metric2?: string; // Name of evaluation metric 2
1109
+ metric2Value?: number; // Value for metric 2
1110
+ metric3?: string; // Name of evaluation metric 3
1111
+ metric3Value?: number; // Value for metric 3
1112
+ createdAt: Date; // When the call was created
1113
+ endedAt?: Date; // When the call ended
1114
+ callDurationMs?: number; // Duration in milliseconds
1115
+ // Additional fields may be present depending on call status
1116
+ }
1117
+ ```
1118
+
1119
+ ### CreateSimulationDto
1120
+
1121
+ Configuration for creating a simulation:
1122
+
1123
+ ```typescript
1124
+ interface CreateSimulationDto {
1125
+ persona: CharacterCreateDto;
1126
+ product: ProductConfig;
1127
+ presentation?: string;
1128
+ scenario: string;
1129
+ objectives?: string;
1130
+ anticipatedObjections?: string;
1131
+ trainingConfiguration: TrainingConfigurationDto;
1132
+ imageId: string;
1133
+ avatarLanguage: AvatarLanguage;
1134
+ }
1135
+ ```
1136
+
1137
+ ### CharacterCreateDto
1138
+
1139
+ AI persona configuration:
1140
+
1141
+ ```typescript
1142
+ interface CharacterCreateDto {
1143
+ name: string;
1144
+ professionalProfile: ProfessionalProfileDto;
1145
+ segment: SegmentType;
1146
+ personalityAndBehaviour: PersonalityAndBehaviourDto;
1147
+ context: ContextDto;
1148
+ assistantGender?: AssistantVoiceGender;
1149
+ }
1150
+ ```
1151
+
1152
+ ### SimulationDetailsDto
1153
+
1154
+ Detailed simulation information returned by `getSimulationDetails()`:
1155
+
1156
+ ```typescript
1157
+ interface SimulationDetailsDto {
1158
+ simulationId: string;
1159
+ phase: CreationPhase;
1160
+ assistantId: string;
1161
+ configuration?: CreateSimulationDto;
1162
+ createdAt: Date;
1163
+ updatedAt: Date;
1164
+ }
1165
+ ```
1166
+
1167
+ ### CreationPhase
1168
+
1169
+ Enum representing the simulation creation phases:
1170
+
1171
+ ```typescript
1172
+ enum CreationPhase {
1173
+ STARTING = 'STARTING',
1174
+ BUILD_HEADER = 'BUILD_HEADER',
1175
+ SEGMENT_SELECTED = 'SEGMENT_SELECTED',
1176
+ BUILD_CONTEXT = 'BUILD_CONTEXT',
1177
+ BUILD_PSYCHOGRAPHICS = 'BUILD_PSYCHOGRAPHICS',
1178
+ BUILD_OBJECTIVES = 'BUILD_OBJECTIVES',
1179
+ PERSONA_ASSEMBLED = 'PERSONA_ASSEMBLED',
1180
+ CORE = 'CORE',
1181
+ BOUNDARIES = 'BOUNDARIES',
1182
+ SPEECH_AND_THOUGHT = 'SPEECH_AND_THOUGHT',
1183
+ CONVERSATION_EVOLUTION = 'CONVERSATION_EVOLUTION',
1184
+ MEMORY = 'MEMORY',
1185
+ OBJECTION_HANDLING = 'OBJECTION_HANDLING',
1186
+ PERFORMANCE_EVALUATION = 'PERFORMANCE_EVALUATION',
1187
+ BEHAVIORAL_FRAMEWORKS = 'BEHAVIORAL_FRAMEWORKS',
1188
+ FINISHED = 'FINISHED',
1189
+ ERROR = 'ERROR',
1190
+ }
1191
+ ```
1192
+
1193
+ ### RecommendationsResponseDto
1194
+
1195
+ Response object from `getRecommendations()`:
1196
+
1197
+ ```typescript
1198
+ interface RecommendationsResponseDto {
1199
+ recommendations: RecommendationItemDto[];
1200
+ strengths: PerformancePatternDto[];
1201
+ improvementAreas: ImprovementAreaDto[];
1202
+ summary: string;
1203
+ callsAnalyzed: number;
1204
+ generatedAt: Date;
1205
+ }
1206
+
1207
+ interface RecommendationItemDto {
1208
+ title: string;
1209
+ description: string;
1210
+ priority: 'high' | 'medium' | 'low';
1211
+ }
1212
+
1213
+ interface PerformancePatternDto {
1214
+ strength: string;
1215
+ frequency: number;
1216
+ }
1217
+
1218
+ interface ImprovementAreaDto {
1219
+ area: string;
1220
+ frequency: number;
1221
+ }
1222
+ ```
1223
+
1224
+ ### PdfSlidesDto
1225
+
1226
+ Simplified data structure for PDF slide records (used in lists):
1227
+
1228
+ ```typescript
1229
+ interface PdfSlidesDto {
1230
+ _id: string;
1231
+ status: PdfSlidesStatus;
1232
+ originalFilename: string;
1233
+ totalSlides?: number;
1234
+ lessonOverview?: string;
1235
+ createdAt: Date;
1236
+ updatedAt: Date;
1237
+ }
1238
+ ```
1239
+
1240
+ ### PdfSlideDto
1241
+
1242
+ Detailed data structure for a single PDF slide analysis:
1243
+
1244
+ ```typescript
1245
+ interface PdfSlideDto {
1246
+ _id: string;
1247
+ status: PdfSlidesStatus;
1248
+ originalFilename: string;
1249
+ totalSlides?: number;
1250
+ lessonOverview?: string;
1251
+ slideAnalysis?: Array<{
1252
+ slideNumber: number;
1253
+ title: string;
1254
+ textExtraction: string;
1255
+ }>;
1256
+ createdAt: Date;
1257
+ updatedAt: Date;
1258
+ }
1259
+ ```
1260
+
1261
+ ### PdfSlidesStatus
1262
+
1263
+ Enum representing the PDF analysis workflow status:
1264
+
1265
+ ```typescript
1266
+ enum PdfSlidesStatus {
1267
+ STARTED = 'started',
1268
+ PROCESSING = 'processing',
1269
+ OVERVIEW = 'overview',
1270
+ COMPLETED = 'completed',
1271
+ FAILED = 'failed',
1272
+ }
1273
+ ```
1274
+
1275
+ ### PdfSlidesAnalysisQueryDto
1276
+
1277
+ Query parameters for retrieving slide analysis records:
1278
+
1279
+ ```typescript
1280
+ interface PdfSlidesAnalysisQueryDto {
1281
+ limit?: 5 | 10 | 25;
1282
+ page?: number;
1283
+ sort?: 'asc' | 'desc';
1284
+ sortBy?: 'createdAt' | 'originalFilename' | 'totalSlides';
1285
+ }
1286
+ ```
1287
+
1288
+ ### AssistantImageDto
1289
+
1290
+ Data structure for assistant images:
1291
+
1292
+ ```typescript
1293
+ interface AssistantImageDto {
1294
+ _id: string;
1295
+ imageUrl: string;
1296
+ }
1297
+ ```
1298
+
1299
+ ### AvatarLanguage
1300
+
1301
+ Enum representing available avatar languages:
1302
+
1303
+ ```typescript
1304
+ enum AvatarLanguage {
1305
+ English = 'en',
1306
+ German = 'de',
1307
+ Spanish = 'es',
1308
+ Italian = 'it',
1309
+ French = 'fr',
1310
+ }
1311
+ ```
1312
+
1313
+ ## Error Handling
1314
+
1315
+ The SDK throws errors for invalid configurations and API failures:
1316
+
1317
+ ```typescript
1318
+ try {
1319
+ const client = new PlatoApiClient({
1320
+ baseUrl: 'https://api.plato.com',
1321
+ token: 'your-token',
1322
+ user: 'your-user',
1323
+ });
1324
+
1325
+ const simulation = await client.createSimulation(simulationConfig);
1326
+ const call = await client.startCall(simulation.simulationId);
1327
+ } catch (error) {
1328
+ console.error('Error:', error.message);
1329
+ }
1330
+ ```
1331
+
1332
+ ## Support
1333
+
1334
+ For support and questions, please contact the development team.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ctchealth/plato-sdk",
3
- "version": "0.0.15",
3
+ "version": "0.0.16",
4
4
  "dependencies": {
5
5
  "tslib": "^2.3.0",
6
6
  "@vapi-ai/web": "2.1.8",
@@ -13,5 +13,5 @@
13
13
  "publishConfig": {
14
14
  "access": "public"
15
15
  },
16
- "types": "./../../apps/plato-lx-api/libs/plato-sdk/src/index.d.ts"
16
+ "types": "./src/index.d.ts"
17
17
  }