-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathvapi.ts
355 lines (314 loc) · 8.99 KB
/
vapi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import type { OpenAI } from 'openai';
import EventEmitter from 'events';
import Daily, {
DailyCall,
DailyEvent,
DailyEventObjectAppMessage,
DailyEventObjectRemoteParticipantsAudioLevel,
DailyEventObjectTrack,
DailyTrackState,
MediaDeviceInfo,
} from '@daily-co/react-native-daily-js';
import { Call, CreateAssistantDTO, CreateSquadDTO, AssistantOverrides } from './api';
import { apiClient } from './apiClient';
export interface AddMessageMessage {
type: 'add-message';
message: OpenAI.ChatCompletionMessageParam;
}
export interface ControlMessages {
type: 'control';
control: 'mute-assistant' | 'unmute-assistant';
}
type VapiClientToServerMessage = AddMessageMessage | ControlMessages;
type VapiEventNames =
| 'call-end'
| 'call-start'
| 'volume-level'
| 'speech-start'
| 'speech-end'
| 'message'
| 'error';
type VapiEventListeners = {
'call-end': () => void;
'call-start': () => void;
'volume-level': (volume: number) => void;
'speech-start': () => void;
'speech-end': () => void;
playable: (track: DailyTrackState) => void;
message: (message: any) => void;
error: (error: any) => void;
};
class VapiEventEmitter extends EventEmitter {
on<E extends VapiEventNames>(event: E, listener: VapiEventListeners[E]): this {
super.on(event, listener);
return this;
}
once<E extends VapiEventNames>(event: E, listener: VapiEventListeners[E]): this {
super.once(event, listener);
return this;
}
emit<E extends VapiEventNames>(event: E, ...args: Parameters<VapiEventListeners[E]>): boolean {
return super.emit(event, ...args);
}
removeListener<E extends VapiEventNames>(event: E, listener: VapiEventListeners[E]): this {
super.removeListener(event, listener);
return this;
}
removeAllListeners(event?: VapiEventNames): this {
super.removeAllListeners(event);
return this;
}
}
export default class Vapi extends VapiEventEmitter {
private started: boolean = false;
private call: DailyCall | null = null;
private cameraDeviceValue: string | null = null;
private cameraDeviceItems: any[] = [];
private audioDeviceValue: string | null = null;
private audioDevicesItems: any[] = [];
private speakingTimeout: NodeJS.Timeout | null = null;
constructor(apiToken: string, apiBaseUrl?: string) {
super();
apiClient.baseUrl = apiBaseUrl ?? 'https://api.vapi.ai';
apiClient.setSecurityData(apiToken);
}
private async cleanup() {
if (!this.call) return;
this.removeEventListeners();
this.started = false;
await this.call.destroy();
this.call = null;
this.speakingTimeout = null;
this.emit('call-end');
}
private onAppMessage(e?: DailyEventObjectAppMessage) {
if (!e) {
return;
}
try {
if (e.data === 'listening') {
return this.emit('call-start');
} else {
try {
const parsedMessage = JSON.parse(e.data);
this.emit('message', parsedMessage);
} catch (parseError) {
console.log('Error parsing message data: ', parseError);
}
}
} catch (e: any) {
console.error(e);
}
}
private onJoinedMeeting() {
this.call?.enumerateDevices().then(({ devices }: any) => {
this.updateAvailableDevices(devices);
this.emit('call-start');
});
}
private onTrackStarted(e: DailyEventObjectTrack | undefined) {
if (
!e ||
!e.participant ||
e.participant?.local ||
e.track.kind !== 'audio' ||
e?.participant?.user_name !== 'Vapi Speaker'
) {
return;
}
this.call?.sendAppMessage('playable');
}
private async refreshSelectedDevice() {
const devicesInUse = await this.call?.getInputDevices();
const cameraDevice = devicesInUse?.camera as MediaDeviceInfo;
if (devicesInUse && cameraDevice?.deviceId) {
try {
this.cameraDeviceValue = cameraDevice.deviceId;
this.call?.setCamera(this.cameraDeviceValue);
} catch (error) {
console.error('error setting camera device', error);
}
}
const speakerDevice = devicesInUse?.speaker as MediaDeviceInfo;
if (devicesInUse && speakerDevice?.deviceId) {
try {
this.audioDeviceValue = speakerDevice.deviceId;
await this.call?.setAudioDevice(this.audioDeviceValue);
} catch (error) {
console.error('error setting audio device', error);
}
}
}
private updateAvailableDevices(devices: MediaDeviceInfo[] | undefined) {
const inputDevices = devices
?.filter((device) => device.kind === 'videoinput')
.map((device) => {
return {
value: device.deviceId,
label: device.label,
originalValue: device,
};
});
this.cameraDeviceItems = inputDevices || [];
const outputDevices = devices
?.filter((device) => device.kind === 'audio')
.map((device) => {
return {
value: device.deviceId,
label: device.label,
originalValue: device,
};
});
this.audioDevicesItems = outputDevices || [];
this.refreshSelectedDevice();
}
private initEventListeners() {
if (!this.call) return;
this.call.on('available-devices-updated', (e) => {
this.updateAvailableDevices(e?.availableDevices);
});
this.call.on('app-message', (e) => {
this.onAppMessage(e);
});
this.call.on('track-started', (e) => {
this.onTrackStarted(e);
});
this.call.on('participant-left', (e) => {
this.cleanup();
});
this.call.on('left-meeting', (e) => {
this.cleanup();
});
this.call.on('error', (e) => {
this.emit('error', e);
this.cleanup();
});
this.call.on('joined-meeting', (e) => {
this.onJoinedMeeting();
});
this.call.on('left-meeting', (e) => {
this.cleanup();
});
}
private removeEventListeners() {
if (!this.call) return;
const events: DailyEvent[] = [
'available-devices-updated',
'app-message',
'track-started',
'participant-left',
'joined-meeting',
'left-meeting',
'error',
];
for (const event of events) {
this.call.off(event, (e: any) => console.log('Off ', e));
}
}
async start(
assistant?: CreateAssistantDTO | string,
assistantOverrides?: AssistantOverrides,
squad?: CreateSquadDTO | string,
): Promise<Call | null> {
if (!assistant && !squad) {
throw new Error('Assistant or assistants must be provided.');
}
if (this.started) {
return null;
}
this.started = true;
const webCall = (
await apiClient.call.callControllerCreateWebCall({
assistant: typeof assistant === 'string' ? undefined : assistant,
assistantId: typeof assistant === 'string' ? assistant : undefined,
assistantOverrides,
squad: typeof squad === 'string' ? undefined : squad,
squadId: typeof squad === 'string' ? squad : undefined,
})
).data;
// @ts-ignore this exists in the response
const roomUrl = webCall.webCallUrl;
if (!roomUrl) {
throw new Error('webCallUrl is not available');
}
try {
this.call = Daily.createCallObject({
audioSource: true,
videoSource: false,
});
this.call.startRemoteParticipantsAudioLevelObserver(100);
this.call.on('remote-participants-audio-level', (e) => {
if (e) this.handleRemoteParticipantsAudioLevel(e);
});
this.initEventListeners();
await this.call.join({
url: roomUrl
});
return webCall;
} catch (e) {
console.error(e);
this.emit('error', e);
this.cleanup();
return null;
}
}
private handleRemoteParticipantsAudioLevel(
e: DailyEventObjectRemoteParticipantsAudioLevel,
) {
const speechLevel = Object.values(e.participantsAudioLevel).reduce(
(a, b) => a + b,
0,
);
this.emit('volume-level', Math.min(1, speechLevel / 0.15));
const isSpeaking = speechLevel > 0.01;
if (!isSpeaking) {
return;
}
if (this.speakingTimeout) {
clearTimeout(this.speakingTimeout);
this.speakingTimeout = null;
} else {
this.emit('speech-start');
}
this.speakingTimeout = setTimeout(() => {
this.emit('speech-end');
this.speakingTimeout = null;
}, 1000);
}
stop(): void {
this.cleanup();
}
send(message: VapiClientToServerMessage): void {
this.call?.sendAppMessage(JSON.stringify(message));
}
setMuted(mute: boolean) {
try {
if (!this.call) {
throw new Error('Call object is not available.');
}
this.call.setLocalAudio(!mute);
} catch (error) {
throw error;
}
}
isMuted() {
try {
if (!this.call) {
return false;
}
return this.call.localAudio() === false;
} catch (error) {
throw error;
}
}
getAudioDevices() {
return this.audioDevicesItems;
}
setAudioDevice(deviceId: string) {
this.audioDeviceValue = deviceId;
this.call?.setAudioDevice(this.audioDeviceValue);
}
getCurrentAudioDevice() {
return this.audioDeviceValue;
}
}