@ctchealth/plato-sdk 0.0.8 → 0.0.9

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.
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Copyright (c) 2025 ctcHealth. All rights reserved.
3
+ *
4
+ * This file is part of the ctcHealth Plato Platform, a proprietary software system developed by ctcHealth.
5
+ *
6
+ * This source code and all related materials are confidential and proprietary to ctcHealth.
7
+ * Unauthorized access, use, copying, modification, distribution, or disclosure is strictly prohibited
8
+ * and may result in disciplinary action and civil and/or criminal penalties.
9
+ *
10
+ * This software is intended solely for authorized use within ctcHealth and its designated partners.
11
+ *
12
+ * For internal use only.
13
+ */
14
+ export enum YearOfExperience {
15
+ '1-5' = '1-5 years',
16
+ '6-10' = '6-10 years',
17
+ '11-20' = '16-20 years',
18
+ '20+' = '20+ years',
19
+ }
20
+
21
+ export enum PracticeType {
22
+ Private = 'Private Practice',
23
+ Hospital = 'Hospital',
24
+ AcademicMedicalCenter = 'Academic Medical Center',
25
+ Clinic = 'Clinic',
26
+ }
27
+ export enum SegmentType {
28
+ Traditionalist = 'The Traditionalist',
29
+ Innovator = 'The Innovator',
30
+ PatientOrientedPhysician = 'The Patient-Oriented Physician',
31
+ FinanciallyDrivenPrescriber = 'The Financially-Driven Prescriber',
32
+ EvidencePurist = 'The Evidence-Purist',
33
+ CostConsciousPrescriber = 'The Cost-Conscious Prescriber',
34
+ }
35
+
36
+ export enum AssistantVoiceGender {
37
+ Male = 'Male',
38
+ Female = 'Female',
39
+ }
40
+
41
+ export class PersonalityAndBehaviourDto {
42
+ riskTolerance!: number;
43
+ researchOrientation!: number;
44
+ recognitionNeed!: number;
45
+ brandLoyalty!: number;
46
+ patientEmpathy!: number;
47
+ }
48
+
49
+ export class ProfessionalProfileDto {
50
+ practiceSettings!: string;
51
+ yearOfExperience!: number;
52
+ specialityAndDepartment!: string;
53
+ location!: string;
54
+ }
55
+
56
+ export class ContextDto {
57
+ subSpecialityOrTherapyFocus!: string;
58
+ typicalPatientMix!: string;
59
+ keyClinicalDrivers!: string;
60
+ }
61
+
62
+ export class CharacterCreateDto {
63
+ name!: string;
64
+ professionalProfile!: ProfessionalProfileDto;
65
+ segment!: SegmentType;
66
+ personalityAndBehaviour!: PersonalityAndBehaviourDto;
67
+ context!: ContextDto;
68
+ assistantGender?: AssistantVoiceGender;
69
+ }
70
+
71
+ export class ProductConfig {
72
+ name!: string;
73
+ description!: string;
74
+ }
75
+
76
+ export class CreateSimulationDto {
77
+ persona!: CharacterCreateDto;
78
+ product!: ProductConfig;
79
+ presentation?: string;
80
+ scenario!: string;
81
+ objectives?: string[];
82
+ anticipatedObjections?: string[];
83
+ }
84
+
85
+ export type RecordingsLimit = 5 | 10 | 25;
86
+
87
+ export class SimulationRecordingsQueryDto {
88
+ limit?: RecordingsLimit;
89
+ page?: number;
90
+ sort?: SortOrder;
91
+ }
92
+
93
+ export enum SortOrder {
94
+ ASC = 'asc',
95
+ DESC = 'desc',
96
+ }
97
+
98
+ export enum RecordingStatus {
99
+ STARTED = 'STARTED',
100
+ PROCESSING = 'PROCESSING',
101
+ FINISHED = 'FINISHED',
102
+ FAILED = 'FAILED',
103
+ }
104
+
105
+ export class SimulationRecordingsDto {
106
+ _id!: string;
107
+ createdAt!: Date;
108
+ recordingStatus?: RecordingStatus;
109
+ }
110
+
111
+ //
112
+ export interface CallCreateDto {
113
+ /**
114
+ * Call ID obtained
115
+ */
116
+ callId: string;
117
+ /**
118
+ * Call Assistant ID
119
+ */
120
+ assistantId: string;
121
+ }
122
+
123
+ export interface CallDTO {
124
+ /**
125
+ * call ID
126
+ */
127
+ _id: string;
128
+ /**
129
+ * call ID obtained
130
+ */
131
+ callId: string;
132
+ /**
133
+ * call User ID
134
+ */
135
+ platoUserId: string;
136
+ /**
137
+ * call Assistant ID
138
+ */
139
+ assistantId: string;
140
+ /**
141
+ * call summary of the conversation
142
+ */
143
+ summary: string;
144
+ /**
145
+ * call transcript of the conversation
146
+ */
147
+ transcript: string;
148
+ /**
149
+ * call feedback provided by the user
150
+ */
151
+ feedback: string;
152
+ /**
153
+ * Success Evaluation returned by model
154
+ */
155
+ successEvaluation: boolean;
156
+ /**
157
+ * call Recording URL
158
+ */
159
+ recordingUrl: string;
160
+ /**
161
+ * Status of recording processing (e.g., 'STARTED', 'PROCESSING', 'FINISHED', 'FAILED')
162
+ */
163
+ recordingStatus?: RecordingStatus;
164
+ /**
165
+ * Date and Time of the creation of the message
166
+ */
167
+ createdAt: Date;
168
+ /**
169
+ * Date and Time of the creation of the message
170
+ */
171
+ endedAt: Date;
172
+ /**
173
+ * Rating of the call given by the user
174
+ */
175
+ rating: number;
176
+ /**
177
+ * Main strenghts of the user conversation based on the analysis of the AI
178
+ */
179
+ strengths: Array<string>;
180
+ /**
181
+ * Main weak points of the user conversation based on the analysis of the AI
182
+ */
183
+ weaknesses: Array<string>;
184
+ /**
185
+ * Name of Metric for the AI feedback report
186
+ */
187
+ metric1: string;
188
+ /**
189
+ * Name of Metric for the AI feedback report
190
+ */
191
+ metric2: string;
192
+ /**
193
+ * Name of Metric for the AI feedback report
194
+ */
195
+ metric3: string;
196
+ /**
197
+ * AI feedback value for Metric 1
198
+ */
199
+ metric1Value: number;
200
+ /**
201
+ * AI feedback value for Metric 2
202
+ */
203
+ metric2Value: number;
204
+ /**
205
+ * AI feedback value for Metric 3
206
+ */
207
+ metric3Value: number;
208
+ /**
209
+ * AI feedback value for the call score
210
+ */
211
+ score?: number;
212
+ /**
213
+ * Defines if the calls will be consider for the memory feature
214
+ */
215
+ inMemory: boolean;
216
+ }
217
+
218
+ export enum CreationStatus {
219
+ CREATING = 'CREATING',
220
+ READY = 'READY',
221
+ ERROR = 'ERROR',
222
+ }
223
+ export enum CreationPhase {
224
+ STARTING = 'STARTING',
225
+ CORE = 'CORE',
226
+ BOUNDARIES = 'BOUNDARIES',
227
+ SPEECH_AND_THOUGHT = 'SPEECH_AND_THOUGHT',
228
+ CONVERSATION_EVOLUTION = 'CONVERSATION_EVOLUTION',
229
+ MEMORY = 'MEMORY',
230
+ FINISHED = 'FINISHED',
231
+ ERROR = 'ERROR',
232
+ }
@@ -0,0 +1,265 @@
1
+ import axios, { AxiosInstance } from 'axios';
2
+ import {
3
+ CallCreateDto,
4
+ CallDTO,
5
+ CreateSimulationDto,
6
+ CreationPhase,
7
+ SimulationRecordingsDto,
8
+ SimulationRecordingsQueryDto,
9
+ } from './plato-intefaces';
10
+ import Vapi from '@vapi-ai/web';
11
+ import { Call } from '@vapi-ai/web/dist/api';
12
+
13
+ export interface ApiClientConfig {
14
+ baseUrl: string;
15
+ token?: string;
16
+ user?: string;
17
+ }
18
+
19
+ /**
20
+ * Event map for call events, providing strict typing for each event's payload.
21
+ */
22
+ export interface CallEventMap {
23
+ 'call-start': void;
24
+ 'call-end': void;
25
+ 'speech-start': void;
26
+ 'speech-end': void;
27
+ error: Error;
28
+ message: {
29
+ type: string;
30
+ role: string;
31
+ transcript?: string;
32
+ transcriptType: 'final' | 'partial';
33
+ toolCallList?: any[];
34
+ toolCalls?: any[];
35
+ [key: string]: any;
36
+ };
37
+ 'volume-level': number;
38
+ }
39
+
40
+ export type CallEventNames = keyof CallEventMap;
41
+
42
+ export type CallEventListener<K extends CallEventNames> = (payload: CallEventMap[K]) => void;
43
+
44
+ export class PlatoApiClient {
45
+ private http: AxiosInstance;
46
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
47
+ private eventListeners: Partial<Record<CallEventNames, Function[]>> = {};
48
+ private callControllerInstance?: Vapi;
49
+ private eventsAttached = false;
50
+ eventNames: CallEventNames[] = [
51
+ 'call-start',
52
+ 'call-end',
53
+ 'speech-start',
54
+ 'speech-end',
55
+ 'error',
56
+ 'message',
57
+ 'volume-level',
58
+ ];
59
+
60
+ constructor(private config: ApiClientConfig) {
61
+ if (!config.baseUrl) {
62
+ throw new Error('baseUrl is required');
63
+ }
64
+ if (!config.token) {
65
+ throw new Error('token is required');
66
+ }
67
+ if (!config.user) {
68
+ throw new Error('user is required');
69
+ }
70
+
71
+ if (config.baseUrl.endsWith('/')) {
72
+ config.baseUrl = config.baseUrl.slice(0, -1);
73
+ }
74
+
75
+ this.http = axios.create({
76
+ baseURL: config.baseUrl,
77
+ headers: {
78
+ 'x-api-key': config.token,
79
+ 'x-api-key-user': config.user,
80
+ },
81
+ });
82
+ }
83
+
84
+ /**
85
+ * Register a listener for a call event with strict typing.
86
+ * @param event Event name
87
+ * @param listener Listener function
88
+ */
89
+ private on<K extends CallEventNames>(event: K, listener: CallEventListener<K>): void {
90
+ if (!this.eventListeners[event]) {
91
+ this.eventListeners[event] = [];
92
+ }
93
+ this.eventListeners[event]!.push(listener);
94
+ if (this.callControllerInstance && !this.eventsAttached) {
95
+ this.attachEvents();
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Remove a listener for a call event with strict typing.
101
+ * @param event Event name
102
+ * @param listener Listener function
103
+ */
104
+ private off<K extends CallEventNames>(event: K, listener: CallEventListener<K>): void {
105
+ if (!this.eventListeners[event]) return;
106
+ this.eventListeners[event] = this.eventListeners[event]!.filter(l => l !== listener);
107
+ }
108
+
109
+ /**
110
+ * Internal: Attach event listeners and propagate to registered listeners.
111
+ */
112
+ private attachEvents(): void {
113
+ if (this.eventsAttached || !this.callControllerInstance) return;
114
+ this.eventsAttached = true;
115
+ const vapi = this.callControllerInstance;
116
+
117
+ this.eventNames.forEach(event => {
118
+ vapi.on(event, (payload: any) => {
119
+ (this.eventListeners[event] || []).forEach(listener => listener(payload));
120
+ });
121
+ });
122
+ }
123
+
124
+ async createSimulation(createSimulationParams: CreateSimulationDto): Promise<{
125
+ simulationId: string;
126
+ phase: CreationPhase;
127
+ }> {
128
+ try {
129
+ const res = await this.http.post('/api/v1/simulation', {
130
+ ...createSimulationParams,
131
+ });
132
+ return {
133
+ simulationId: res.data.simulationId,
134
+ phase: res.data.phase,
135
+ };
136
+ } catch (e) {
137
+ if (axios.isAxiosError(e)) {
138
+ console.error('Error creating simulation:', e.response?.data.message);
139
+ }
140
+ throw e;
141
+ }
142
+ }
143
+
144
+ async checkSimulationStatus(simulationId: string): Promise<{
145
+ phase: CreationPhase;
146
+ }> {
147
+ const res = await this.http.get(`/api/v1/simulation/status/${simulationId}`);
148
+
149
+ return res.data;
150
+ }
151
+
152
+ async getCallDetails(callId: string): Promise<CallDTO> {
153
+ try {
154
+ const res = await this.http.get(`/api/v1/simulation/call/${callId}`);
155
+ return res.data as CallDTO;
156
+ } catch (e) {
157
+ if (axios.isAxiosError(e)) {
158
+ console.error('Error getting call details:', e.response?.data.message);
159
+ }
160
+ throw e;
161
+ }
162
+ }
163
+
164
+ async getCallRecordings(
165
+ queryParams: SimulationRecordingsQueryDto
166
+ ): Promise<SimulationRecordingsDto[]> {
167
+ try {
168
+ const res = await this.http.get(`/api/v1/simulation/call/recordings`, {
169
+ params: queryParams,
170
+ });
171
+ return res.data as SimulationRecordingsDto[];
172
+ } catch (e) {
173
+ if (axios.isAxiosError(e)) {
174
+ console.error('Error getting call recordings:', e.response?.data.message);
175
+ }
176
+ throw e;
177
+ }
178
+ }
179
+
180
+ async getCallRecording(callId: string): Promise<string> {
181
+ try {
182
+ const res = await this.http.get(`/api/v1/simulation/call/recordings/${callId}`);
183
+ return res.data as string;
184
+ } catch (e) {
185
+ if (axios.isAxiosError(e)) {
186
+ console.error('Error getting call recording:', e.response?.data.message);
187
+ }
188
+ throw e;
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Remove all listeners for all call events.
194
+ */
195
+ private removeAllEventListeners(): void {
196
+ if (!this.callControllerInstance) return;
197
+ this.eventNames.forEach(event => {
198
+ (this.eventListeners[event] || []).forEach(listener => {
199
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
200
+ // @ts-expect-error
201
+ this.callControllerInstance?.off(event, listener);
202
+ });
203
+ this.eventListeners[event] = [];
204
+ });
205
+ this.eventsAttached = false;
206
+ }
207
+
208
+ async startCall(simulationId: string) {
209
+ this.callControllerInstance = new Vapi(
210
+ 'f07d17ec-d4e6-487d-a0b9-0539c01aecbb',
211
+ 'https://db41aykk1gw9e.cloudfront.net' // base url
212
+ );
213
+ if (!this.eventsAttached) {
214
+ this.attachEvents();
215
+ }
216
+ const { data } = await this.http.get(`/api/v1/simulation/${simulationId}`);
217
+ const assistantId = data as string;
218
+ const call: Call | null = await this.callControllerInstance.start(assistantId);
219
+
220
+ if (!call || !call.assistantId) {
221
+ throw new Error('Cannot start a call, please try again later');
222
+ }
223
+ try {
224
+ const apiCall = await this.createCall({
225
+ callId: call.id,
226
+ assistantId: call.assistantId,
227
+ });
228
+
229
+ // Return stopCall, callId, and event subscription methods with strict typing
230
+ return {
231
+ stopCall: () => {
232
+ this.callControllerInstance?.stop();
233
+ this.removeAllEventListeners();
234
+ },
235
+ callId: apiCall._id,
236
+ /**
237
+ * Subscribe to call events for this call with strict typing.
238
+ * @param event Event name
239
+ * @param listener Listener function
240
+ */
241
+ on: <K extends CallEventNames>(event: K, listener: CallEventListener<K>) =>
242
+ this.on(event, listener),
243
+ /**
244
+ * Unsubscribe from call events for this call with strict typing.
245
+ * @param event Event name
246
+ * @param listener Listener function
247
+ */
248
+ off: <K extends CallEventNames>(event: K, listener: CallEventListener<K>) =>
249
+ this.off(event, listener),
250
+ };
251
+ } catch (e) {
252
+ this.callControllerInstance?.stop();
253
+ this.removeAllEventListeners();
254
+ throw e;
255
+ }
256
+ }
257
+
258
+ private async createCall(payload: CallCreateDto) {
259
+ const response = await this.http.post('/api/v1/simulation/call', {
260
+ ...payload,
261
+ });
262
+
263
+ return response.data as CallDTO;
264
+ }
265
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "module": "commonjs",
5
+ "forceConsistentCasingInFileNames": true,
6
+ "strict": true,
7
+ "noImplicitOverride": true,
8
+ "noImplicitReturns": true,
9
+ "noFallthroughCasesInSwitch": true,
10
+ "noPropertyAccessFromIndexSignature": true
11
+ },
12
+ "files": [],
13
+ "include": [],
14
+ "references": [
15
+ {
16
+ "path": "./tsconfig.lib.json"
17
+ },
18
+ {
19
+ "path": "./tsconfig.spec.json"
20
+ }
21
+ ]
22
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "../../dist/out-tsc",
5
+ "declaration": true,
6
+ "types": ["node"],
7
+ "esModuleInterop": true
8
+ },
9
+ "include": ["src/**/*.ts"],
10
+ "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
11
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "../../dist/out-tsc",
5
+ "module": "commonjs",
6
+ "moduleResolution": "node10",
7
+ "types": ["jest", "node"]
8
+ },
9
+ "include": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts", "src/**/*.d.ts"]
10
+ }
package/src/index.js DELETED
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- tslib_1.__exportStar(require("./lib/plato-sdk"), exports);
5
- //# sourceMappingURL=index.js.map
package/src/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../libs/plato-sdk/src/index.ts"],"names":[],"mappings":";;;AAAA,0DAAgC"}