-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathuseVapiCall.ts
More file actions
342 lines (306 loc) · 8.82 KB
/
useVapiCall.ts
File metadata and controls
342 lines (306 loc) · 8.82 KB
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
import { useState, useEffect, useRef, useCallback } from 'react';
import Vapi from '@vapi-ai/web';
import * as vapiCallStorage from '../utils/vapiCallStorage';
import type { StorageType } from '../utils/vapiCallStorage';
export interface VapiCallState {
isCallActive: boolean;
isSpeaking: boolean;
volumeLevel: number;
connectionStatus: 'disconnected' | 'connecting' | 'connected';
isMuted: boolean;
}
export interface VapiCallHandlers {
startCall: () => Promise<void>;
endCall: (opts?: { force?: boolean }) => Promise<void>;
toggleCall: (opts?: { force?: boolean }) => Promise<void>;
toggleMute: () => void;
reconnect: () => Promise<void>;
clearStoredCall: () => void;
}
export interface UseVapiCallOptions {
publicKey: string;
callOptions: any;
apiUrl?: string;
enabled?: boolean;
voiceAutoReconnect?: boolean;
voiceReconnectStorage?: StorageType;
reconnectStorageKey?: string;
onCallStart?: () => void;
onCallEnd?: () => void;
onMessage?: (message: any) => void;
onError?: (error: Error) => void;
onTranscript?: (transcript: {
role: string;
text: string;
timestamp: Date;
}) => void;
}
export const useVapiCall = ({
publicKey,
callOptions,
apiUrl,
enabled = true,
voiceAutoReconnect = false,
voiceReconnectStorage = 'session',
reconnectStorageKey = 'vapi_widget_web_call',
onCallStart,
onCallEnd,
onMessage,
onError,
onTranscript,
}: UseVapiCallOptions): VapiCallState & VapiCallHandlers => {
const [vapi] = useState(() =>
publicKey ? new Vapi(publicKey, apiUrl) : null
);
const [isCallActive, setIsCallActive] = useState(false);
const [isSpeaking, setIsSpeaking] = useState(false);
const [isMuted, setIsMuted] = useState(false);
const [volumeLevel, setVolumeLevel] = useState(0);
const [connectionStatus, setConnectionStatus] = useState<
'disconnected' | 'connecting' | 'connected'
>('disconnected');
const callbacksRef = useRef({
onCallStart,
onCallEnd,
onMessage,
onError,
onTranscript,
});
useEffect(() => {
callbacksRef.current = {
onCallStart,
onCallEnd,
onMessage,
onError,
onTranscript,
};
});
useEffect(() => {
if (!vapi) {
return;
}
const handleCallStart = () => {
setIsCallActive(true);
setConnectionStatus('connected');
callbacksRef.current.onCallStart?.();
};
const handleCallEnd = () => {
setIsCallActive(false);
setConnectionStatus('disconnected');
setVolumeLevel(0);
setIsSpeaking(false);
setIsMuted(false);
// Clear stored call data on successful call end
vapiCallStorage.clearStoredCall(
reconnectStorageKey,
voiceReconnectStorage
);
callbacksRef.current.onCallEnd?.();
};
const handleSpeechStart = () => {
setIsSpeaking(true);
};
const handleSpeechEnd = () => {
setIsSpeaking(false);
};
const handleVolumeLevel = (volume: number) => {
setVolumeLevel(volume);
};
const handleMessage = (message: any) => {
if (message.type === 'transcript' && message.transcriptType === 'final') {
if (message.role === 'user' || message.role === 'assistant') {
callbacksRef.current.onTranscript?.({
role: message.role,
text: message.transcript,
timestamp: new Date(),
});
}
}
callbacksRef.current.onMessage?.(message);
};
const handleError = (error: Error) => {
console.error('Vapi error:', error);
setConnectionStatus('disconnected');
setIsCallActive(false);
setIsSpeaking(false);
callbacksRef.current.onError?.(error);
};
vapi.on('call-start', handleCallStart);
vapi.on('call-end', handleCallEnd);
vapi.on('speech-start', handleSpeechStart);
vapi.on('speech-end', handleSpeechEnd);
vapi.on('volume-level', handleVolumeLevel);
vapi.on('message', handleMessage);
vapi.on('error', handleError);
return () => {
vapi.removeListener('call-start', handleCallStart);
vapi.removeListener('call-end', handleCallEnd);
vapi.removeListener('speech-start', handleSpeechStart);
vapi.removeListener('speech-end', handleSpeechEnd);
vapi.removeListener('volume-level', handleVolumeLevel);
vapi.removeListener('message', handleMessage);
vapi.removeListener('error', handleError);
};
}, [vapi, reconnectStorageKey, voiceReconnectStorage]);
useEffect(() => {
return () => {
if (vapi) {
vapi.stop();
}
};
}, [vapi]);
const startCall = useCallback(async () => {
if (!vapi || !enabled) {
console.error('Cannot start call: no vapi instance or not enabled');
return;
}
try {
console.log('Starting call with configuration:', callOptions);
console.log('Starting call with options:', {
voiceAutoReconnect,
});
setConnectionStatus('connecting');
const call = await vapi.start(
// assistant
callOptions,
// assistant overrides,
undefined,
// squad
undefined,
// workflow
undefined,
// workflow overrides
undefined,
// options
{
roomDeleteOnUserLeaveEnabled: !voiceAutoReconnect,
}
);
// Store call data for reconnection if call was successful and auto-reconnect is enabled
if (call && voiceAutoReconnect) {
vapiCallStorage.storeCallData(
reconnectStorageKey,
call,
callOptions,
voiceReconnectStorage
);
}
} catch (error) {
console.error('Error starting call:', error);
setConnectionStatus('disconnected');
callbacksRef.current.onError?.(error as Error);
}
}, [
vapi,
callOptions,
enabled,
voiceAutoReconnect,
voiceReconnectStorage,
reconnectStorageKey,
]);
const endCall = useCallback(
async ({ force = false }: { force?: boolean } = {}) => {
if (!vapi) {
console.log('Cannot end call: no vapi instance');
return;
}
console.log('Ending call with force:', force);
if (force) {
// end vapi call and delete daily room
vapi.end();
} else {
// simply disconnect from daily room
vapi.stop();
}
},
[vapi]
);
const toggleCall = useCallback(
async ({ force = false }: { force?: boolean } = {}) => {
if (isCallActive) {
await endCall({ force });
} else {
await startCall();
}
},
[isCallActive, startCall, endCall]
);
const toggleMute = useCallback(() => {
if (!vapi || !isCallActive) {
console.log('Cannot toggle mute: no vapi instance or call not active');
return;
}
const newMutedState = !isMuted;
vapi.setMuted(newMutedState);
setIsMuted(newMutedState);
}, [vapi, isCallActive, isMuted]);
const reconnect = useCallback(async () => {
if (!vapi || !enabled) {
console.error('Cannot reconnect: no vapi instance or not enabled');
return;
}
const storedData = vapiCallStorage.getStoredCallData(
reconnectStorageKey,
voiceReconnectStorage
);
if (!storedData) {
console.warn('No stored call data found for reconnection');
return;
}
// Check if callOptions match before reconnecting
if (
!vapiCallStorage.areCallOptionsEqual(storedData.callOptions, callOptions)
) {
console.warn(
'CallOptions have changed since last call, clearing stored data and skipping reconnection'
);
vapiCallStorage.clearStoredCall(
reconnectStorageKey,
voiceReconnectStorage
);
return;
}
setConnectionStatus('connecting');
try {
await vapi.reconnect({
webCallUrl: storedData.webCallUrl,
id: storedData.id,
artifactPlan: storedData.artifactPlan,
assistant: storedData.assistant,
});
console.log('Successfully reconnected to call');
} catch (error) {
setConnectionStatus('disconnected');
console.error('Reconnection failed:', error);
vapiCallStorage.clearStoredCall(
reconnectStorageKey,
voiceReconnectStorage
);
callbacksRef.current.onError?.(error as Error);
}
}, [vapi, enabled, reconnectStorageKey, voiceReconnectStorage, callOptions]);
const clearStoredCall = useCallback(() => {
vapiCallStorage.clearStoredCall(reconnectStorageKey, voiceReconnectStorage);
}, [reconnectStorageKey, voiceReconnectStorage]);
useEffect(() => {
if (!vapi || !enabled || !voiceAutoReconnect) {
return;
}
reconnect();
}, [vapi, enabled, voiceAutoReconnect, reconnect, reconnectStorageKey]);
return {
// State
isCallActive,
isSpeaking,
volumeLevel,
connectionStatus,
isMuted,
// Handlers
startCall,
endCall,
toggleCall,
toggleMute,
reconnect,
clearStoredCall,
};
};