-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoutbound.js
More file actions
334 lines (291 loc) · 9.92 KB
/
Copy pathoutbound.js
File metadata and controls
334 lines (291 loc) · 9.92 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
import fastifyFormBody from "@fastify/formbody";
import fastifyWs from "@fastify/websocket";
import dotenv from "dotenv";
import Fastify from "fastify";
import Twilio from "twilio";
import WebSocket from "ws";
// Load environment variables from .env file
dotenv.config();
// Check for required environment variables
const {
ELEVENLABS_API_KEY,
ELEVENLABS_AGENT_ID,
TWILIO_ACCOUNT_SID,
TWILIO_AUTH_TOKEN,
TWILIO_PHONE_NUMBER,
} = process.env;
if (
!ELEVENLABS_API_KEY ||
!ELEVENLABS_AGENT_ID ||
!TWILIO_ACCOUNT_SID ||
!TWILIO_AUTH_TOKEN ||
!TWILIO_PHONE_NUMBER
) {
console.error("Missing required environment variables");
throw new Error("Missing required environment variables");
}
// Initialize Fastify server
const fastify = Fastify();
fastify.register(fastifyFormBody);
fastify.register(fastifyWs);
const PORT = process.env.PORT || 8000;
// Root route for health check
fastify.get("/", async (_, reply) => {
reply.send({ message: "Server is running" });
});
// Initialize Twilio client
const twilioClient = new Twilio(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
// Helper function to get signed URL for authenticated conversations
async function getSignedUrl() {
try {
const response = await fetch(
`https://api.elevenlabs.io/v1/convai/conversation/get_signed_url?agent_id=${ELEVENLABS_AGENT_ID}`,
{
method: "GET",
headers: {
"xi-api-key": ELEVENLABS_API_KEY,
},
}
);
if (!response.ok) {
throw new Error(`Failed to get signed URL: ${response.statusText}`);
}
const data = await response.json();
return data.signed_url;
} catch (error) {
console.error("Error getting signed URL:", error);
throw error;
}
}
// Route to initiate outbound calls
fastify.post("/outbound-call", async (request, reply) => {
const { number, prompt, first_message } = request.body;
if (!number) {
return reply.code(400).send({ error: "Phone number is required" });
}
try {
const call = await twilioClient.calls.create({
from: TWILIO_PHONE_NUMBER,
to: number,
url: `https://${
request.headers.host
}/outbound-call-twiml?prompt=${encodeURIComponent(
prompt
)}&first_message=${encodeURIComponent(first_message)}`,
});
reply.send({
success: true,
message: "Call initiated",
callSid: call.sid,
});
} catch (error) {
console.error("Error initiating outbound call:", error);
reply.code(500).send({
success: false,
error: "Failed to initiate call",
});
}
});
// TwiML route for outbound calls
fastify.all("/outbound-call-twiml", async (request, reply) => {
const prompt = request.query.prompt || "";
const first_message = request.query.first_message || "";
const twimlResponse = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Connect>
<Stream url="wss://${request.headers.host}/outbound-media-stream">
<Parameter name="prompt" value="${prompt}" />
<Parameter name="first_message" value="${first_message}" />
</Stream>
</Connect>
</Response>`;
reply.type("text/xml").send(twimlResponse);
});
// WebSocket route for handling media streams
fastify.register(async fastifyInstance => {
fastifyInstance.get(
"/outbound-media-stream",
{ websocket: true },
(ws, req) => {
console.info("[Server] Twilio connected to outbound media stream");
// Variables to track the call
let streamSid = null;
let callSid = null;
let elevenLabsWs = null;
let customParameters = null; // Add this to store parameters
// Handle WebSocket errors
ws.on("error", console.error);
// Set up ElevenLabs connection
const setupElevenLabs = async () => {
try {
const signedUrl = await getSignedUrl();
elevenLabsWs = new WebSocket(signedUrl);
elevenLabsWs.on("open", () => {
console.log("[ElevenLabs] Connected to Conversational AI");
// Send initial configuration with prompt and first message
const initialConfig = {
type: "conversation_initiation_client_data",
conversation_config_override: {
agent: {
prompt: {
prompt:
customParameters?.prompt ||
"you are a gary from the phone store",
},
first_message:
customParameters?.first_message ||
"hey there! how can I help you today?",
},
},
};
console.log(
"[ElevenLabs] Sending initial config with prompt:",
initialConfig.conversation_config_override.agent.prompt.prompt
);
// Send the configuration to ElevenLabs
elevenLabsWs.send(JSON.stringify(initialConfig));
});
elevenLabsWs.on("message", data => {
try {
const message = JSON.parse(data);
switch (message.type) {
case "conversation_initiation_metadata":
console.log("[ElevenLabs] Received initiation metadata");
break;
case "audio":
if (streamSid) {
if (message.audio?.chunk) {
const audioData = {
event: "media",
streamSid,
media: {
payload: message.audio.chunk,
},
};
ws.send(JSON.stringify(audioData));
} else if (message.audio_event?.audio_base_64) {
const audioData = {
event: "media",
streamSid,
media: {
payload: message.audio_event.audio_base_64,
},
};
ws.send(JSON.stringify(audioData));
}
} else {
console.log(
"[ElevenLabs] Received audio but no StreamSid yet"
);
}
break;
case "interruption":
if (streamSid) {
ws.send(
JSON.stringify({
event: "clear",
streamSid,
})
);
}
break;
case "ping":
if (message.ping_event?.event_id) {
elevenLabsWs.send(
JSON.stringify({
type: "pong",
event_id: message.ping_event.event_id,
})
);
}
break;
case "agent_response":
console.log(
`[Twilio] Agent response: ${message.agent_response_event?.agent_response}`
);
break;
case "user_transcript":
console.log(
`[Twilio] User transcript: ${message.user_transcription_event?.user_transcript}`
);
break;
default:
console.log(
`[ElevenLabs] Unhandled message type: ${message.type}`
);
}
} catch (error) {
console.error("[ElevenLabs] Error processing message:", error);
}
});
elevenLabsWs.on("error", error => {
console.error("[ElevenLabs] WebSocket error:", error);
});
elevenLabsWs.on("close", () => {
console.log("[ElevenLabs] Disconnected");
});
} catch (error) {
console.error("[ElevenLabs] Setup error:", error);
}
};
// Set up ElevenLabs connection
setupElevenLabs();
// Handle messages from Twilio
ws.on("message", message => {
try {
const msg = JSON.parse(message);
if (msg.event !== "media") {
console.log(`[Twilio] Received event: ${msg.event}`);
}
switch (msg.event) {
case "start":
streamSid = msg.start.streamSid;
callSid = msg.start.callSid;
customParameters = msg.start.customParameters; // Store parameters
console.log(
`[Twilio] Stream started - StreamSid: ${streamSid}, CallSid: ${callSid}`
);
console.log("[Twilio] Start parameters:", customParameters);
break;
case "media":
if (elevenLabsWs?.readyState === WebSocket.OPEN) {
const audioMessage = {
user_audio_chunk: Buffer.from(
msg.media.payload,
"base64"
).toString("base64"),
};
elevenLabsWs.send(JSON.stringify(audioMessage));
}
break;
case "stop":
console.log(`[Twilio] Stream ${streamSid} ended`);
if (elevenLabsWs?.readyState === WebSocket.OPEN) {
elevenLabsWs.close();
}
break;
default:
console.log(`[Twilio] Unhandled event: ${msg.event}`);
}
} catch (error) {
console.error("[Twilio] Error processing message:", error);
}
});
// Handle WebSocket closure
ws.on("close", () => {
console.log("[Twilio] Client disconnected");
if (elevenLabsWs?.readyState === WebSocket.OPEN) {
elevenLabsWs.close();
}
});
}
);
});
// Start the Fastify server
fastify.listen({ port: PORT }, err => {
if (err) {
console.error("Error starting server:", err);
process.exit(1);
}
console.log(`[Server] Listening on port ${PORT}`);
});