-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAgent.tsx
331 lines (292 loc) · 10.8 KB
/
Agent.tsx
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
"use client";
import Image from "next/image";
import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { vapi } from "@/lib/vapi.sdk";
import { interviewer } from "@/constants";
import { createFeedback } from "@/lib/actions/general.action";
import CallHint from "@/components/CallHint";
enum CallStatus {
INACTIVE = "INACTIVE",
CONNECTING = "CONNECTING",
ACTIVE = "ACTIVE",
FINISHED = "FINISHED",
}
interface SavedMessage {
role: "user" | "system" | "assistant";
content: string;
}
const Agent = ({
userName,
userId,
interviewId,
feedbackId,
type,
questions,
userAvatar,
}: AgentProps) => {
const router = useRouter();
const [callStatus, setCallStatus] = useState<CallStatus>(CallStatus.INACTIVE);
const [messages, setMessages] = useState<SavedMessage[]>([]);
const [isSpeaking, setIsSpeaking] = useState(false);
const [lastMessage, setLastMessage] = useState<string>("");
const [showCallHint, setShowCallHint] = useState(true);
const [lastActivityTimestamp, setLastActivityTimestamp] = useState<number>(Date.now());
const INACTIVITY_TIMEOUT = process.env.NEXT_PUBLIC_VAPI_INACTIVITY_TIMEOUT
? parseInt(process.env.NEXT_PUBLIC_VAPI_INACTIVITY_TIMEOUT)
: 10000; // time of inactivity will end the call
// Add question tracking
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const totalQuestions = questions?.length || 0;
const handleDisconnect = useCallback(() => {
setCallStatus(CallStatus.FINISHED);
vapi.stop();
}, []);
// Inactivity monitor
useEffect(() => {
if (callStatus !== CallStatus.ACTIVE) return;
const inactivityTimer = setInterval(() => {
const now = Date.now();
if (now - lastActivityTimestamp > INACTIVITY_TIMEOUT) {
console.log("Inactivity timeout reached, ending call");
handleDisconnect();
}
}, 5000); // Check every 5 seconds
return () => clearInterval(inactivityTimer);
}, [callStatus, lastActivityTimestamp, handleDisconnect, INACTIVITY_TIMEOUT]);
// VAPI event handlers
useEffect(() => {
const onCallStart = () => {
setCallStatus(CallStatus.ACTIVE);
setLastActivityTimestamp(Date.now());
};
const onCallEnd = () => {
setCallStatus(CallStatus.FINISHED);
};
const onMessage = (message: Message) => {
if (message.type === "transcript" && message.transcriptType === "final") {
setLastActivityTimestamp(Date.now());
const newMessage = { role: message.role, content: message.transcript };
setMessages((prev) => [...prev, newMessage]);
// Track question progress - only increment counter when AI asks a MAIN question
// We'll use a more sophisticated approach to identify main questions
if (message.role === "assistant" &&
totalQuestions > 0 &&
currentQuestionIndex < totalQuestions) {
// Check if this message contains a question that matches one of our prepared questions
if (message.transcript.includes("?") && questions) {
// Try to match this message with one of our prepared questions
const isMainQuestion = questions.some(question => {
// Create a simplified version of both texts for comparison (lowercase, no punctuation)
const simplifiedTranscript = message.transcript.toLowerCase().replace(/[^\w\s]/g, '');
const simplifiedQuestion = question.toLowerCase().replace(/[^\w\s]/g, '');
// Check if the transcript contains a significant portion of the question
// This helps match even if the AI rephrases slightly
return simplifiedTranscript.includes(simplifiedQuestion.substring(0, Math.min(30, simplifiedQuestion.length)));
});
if (isMainQuestion) {
setCurrentQuestionIndex(prev => prev + 1);
console.log(`Question ${currentQuestionIndex + 1}/${totalQuestions} asked (matched with prepared question)`);
}
}
}
// Auto-end call when all questions have been asked AND answered
// Only consider ending after the last question has been asked
if (currentQuestionIndex >= totalQuestions && totalQuestions > 0) {
// Only end the call after the user has responded to the last question
if (message.role === "user") {
console.log("All questions completed and user has responded, ending call automatically");
// Add a longer delay to allow for final exchange and closing remarks
setTimeout(() => {
handleDisconnect();
}, 15000); // 15 second grace period after user's final answer
}
}
}
};
const onSpeechStart = () => {
setLastActivityTimestamp(Date.now()); // Update timestamp when speech starts
setIsSpeaking(true);
};
const onSpeechEnd = () => {
setIsSpeaking(false);
};
const onError = (error: Error) => {
console.log("Error:", error);
// More robust error handling for meeting ended errors
if (
(typeof error === 'object' && error !== null) &&
(
// Check various possible error message formats
(error.message && error.message.includes("Meeting has ended")) ||
(error.toString().includes("Meeting has ended")) ||
(JSON.stringify(error).includes("Meeting has ended"))
)
) {
console.log("Detected meeting end, transitioning to FINISHED state");
setCallStatus(CallStatus.FINISHED);
vapi.stop(); // Ensure VAPI is properly stopped
}
};
vapi.on("call-start", onCallStart);
vapi.on("call-end", onCallEnd);
vapi.on("message", onMessage);
vapi.on("speech-start", onSpeechStart);
vapi.on("speech-end", onSpeechEnd);
vapi.on("error", onError);
return () => {
vapi.off("call-start", onCallStart);
vapi.off("call-end", onCallEnd);
vapi.off("message", onMessage);
vapi.off("speech-start", onSpeechStart);
vapi.off("speech-end", onSpeechEnd);
vapi.off("error", onError);
};
}, [currentQuestionIndex, totalQuestions, handleDisconnect, questions]);
// Handle messages and call status changes
useEffect(() => {
if (messages.length > 0) {
setLastMessage(messages[messages.length - 1].content);
}
const handleGenerateFeedback = async (messages: SavedMessage[]) => {
toast.loading("Generating feedback from your interview...", {
duration: 5000,
id: "feedback-toast"
});
const { success, feedbackId: id } = await createFeedback({
interviewId: interviewId!,
userId: userId!,
transcript: messages,
feedbackId,
});
if (success && id) {
toast.success("Feedback generated successfully!", {
id: "feedback-toast"
});
router.push(`/interview/${interviewId}/feedback`);
} else {
console.log("Error saving feedback");
toast.error("Failed to generate feedback", {
id: "feedback-toast"
});
router.push("/");
}
};
if (callStatus === CallStatus.FINISHED) {
if (type === "generate") {
toast.success("Interview generated successfully!", {
duration: 3000,
id: "generate-toast"
});
router.push("/");
} else {
handleGenerateFeedback(messages);
}
}
}, [messages, callStatus, feedbackId, interviewId, router, type, userId]);
const handleCall = async () => {
setCallStatus(CallStatus.CONNECTING);
if (type === "generate") {
toast.loading("Generating your interview questions...", {
duration: 10000,
id: "generate-toast"
});
await vapi.start(process.env.NEXT_PUBLIC_VAPI_WORKFLOW_ID!, {
variableValues: {
username: userName,
userid: userId,
},
});
} else {
let formattedQuestions = "";
if (questions) {
formattedQuestions = questions
.map((question) => `- ${question}`)
.join("\n");
}
await vapi.start(interviewer, {
variableValues: {
questions: formattedQuestions,
},
});
}
};
return (
<>
<div className="call-view">
{/* AI Interviewer Card */}
<div className="card-interviewer">
<div className="avatar">
<Image src="/ai-avatar-512.png" alt="AI Avatar" width={110} height={110} className="object-cover" />
{isSpeaking && <span className="animate-speak" />}
</div>
<h3>AI Interviewer</h3>
</div>
{/* User Profile Card */}
<div className="card-border">
<div className="card-content">
<Image
src={userAvatar || "/user-avatar.jpg"}
alt="profile-image"
width={539}
height={539}
className="rounded-full object-cover size-[120px]"
/>
<h3>{userName}</h3>
</div>
</div>
</div>
{messages.length > 0 && (
<div className="transcript-border">
<div className="transcript">
<p
key={lastMessage}
className={cn(
"transition-opacity duration-500 opacity-0",
"animate-fadeIn opacity-100"
)}
>
{lastMessage}
</p>
</div>
</div>
)}
<div className="w-full flex justify-center relative">
{callStatus === CallStatus.INACTIVE && showCallHint && (
<CallHint
targetId="call-button"
timeoutDuration={10000}
text={type === "generate" ? "Click CALL to generate the interview" : "Click CALL to start the interview"}
onDismiss={() => setShowCallHint(false)}
/>
)}
{callStatus !== "ACTIVE" ? (
<button
id="call-button"
className="relative btn-call"
onClick={() => handleCall()}
>
<span
className={cn(
"absolute animate-ping rounded-full opacity-75",
callStatus !== "CONNECTING" && "hidden"
)}
/>
<span className="relative">
{callStatus === "INACTIVE" || callStatus === "FINISHED"
? "Call"
: <span className="dots-loading">. . .</span>}
</span>
</button>
) : (
<button className="btn-disconnect cursor-pointer" onClick={() => handleDisconnect()}>
End
</button>
)}
</div>
</>
);
};
export default Agent;