Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the issue of Twilio sometimes starting a new websocket connection for the same call concurrently #61

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 98 additions & 54 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,94 +17,138 @@ ExpressWs(app);

const PORT = process.env.PORT || 3000;

async function getCallerNumber(call) {
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);

const response = await client.calls(call.callSid).fetch();
return response.from;
}

app.post('/incoming', (req, res) => {
try {
const response = new VoiceResponse();
const connect = response.connect();
connect.stream({ url: `wss://${process.env.SERVER}/connection` });

res.type('text/xml');
res.end(response.toString());
} catch (err) {
console.log(err);
}
});

const activeCalls = {};

function bindCall(call) {
const { streamSid, gptService, streamService, transcriptionService, ttsService, marks, ws } = call;

let interactionCount = 0;

transcriptionService.on('utterance', async (text) => {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all of this code is just moved from below into this bindCall wrapper.

// This is a bit of a hack to filter out empty utterances
if(marks.length > 0 && text?.length > 5) {
console.log('Twilio -> Interruption, Clearing stream'.red);
ws.send(
JSON.stringify({
streamSid,
event: 'clear',
})
);
}
});

transcriptionService.on('transcription', async (text) => {
if (!text) { return; }
console.log(`Interaction ${interactionCount} – STT -> GPT: ${text}`.yellow);
gptService.completion(text, interactionCount);
interactionCount += 1;
});

gptService.on('gptreply', async (gptReply, icount) => {
console.log(`Interaction ${icount}: GPT -> TTS: ${gptReply.partialResponse}`.green );
ttsService.generate(gptReply, icount);
});

ttsService.on('speech', (responseIndex, audio, label, icount) => {
console.log(`Interaction ${icount}: TTS -> TWILIO: ${label}`.blue);

streamService.buffer(responseIndex, audio);
});

streamService.on('audiosent', (markLabel) => {
marks.push(markLabel);
});
}

app.ws('/connection', (ws) => {
try {
ws.on('error', console.error);
// Filled in from start message
let streamSid;
let callSid;

const gptService = new GptService();
const streamService = new StreamService(ws);
const transcriptionService = new TranscriptionService();
const ttsService = new TextToSpeechService({});

let marks = [];
let interactionCount = 0;

let call = null;

// Incoming from MediaStream
ws.on('message', function message(data) {
const msg = JSON.parse(data);
if (msg.event === 'start') {
streamSid = msg.start.streamSid;
callSid = msg.start.callSid;

streamService.setStreamSid(streamSid);
gptService.setCallSid(callSid);

// Set RECORDING_ENABLED='true' in .env to record calls
recordingService(ttsService, callSid).then(() => {
console.log(`Twilio -> Starting Media Stream for ${streamSid}`.underline.red);
ttsService.generate({partialResponseIndex: null, partialResponse: 'Hello! I understand you\'re looking for a pair of AirPods, is that correct?'}, 0);

getCallerNumber(msg.start).then((number) => {
if (activeCalls[number]) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refuse to initiate multiple streams for the same inbound/from caller number

return;
}
console.log(`Twilio -> received new call from ${number}`);

const transcriptionService = new TranscriptionService();

call = {
callSid: callSid,
streamSid: streamSid,
gptService: new GptService(),
streamService: new StreamService(ws),
transcriptionService: transcriptionService,
ttsService: new TextToSpeechService({}),
marks: [],
ws: ws
};
activeCalls[number] = call;
bindCall(call);

call.streamService.setStreamSid(streamSid);
call.gptService.setCallSid(callSid);

// Set RECORDING_ENABLED='true' in .env to record calls
recordingService(call.ttsService, callSid).then(() => {
console.log(`Twilio -> Starting Media Stream for ${streamSid}`.underline.red);
call.ttsService.generate({partialResponseIndex: null, partialResponse: 'Hello! I understand you\'re looking for a pair of AirPods, is that correct?'}, 0);
});
});
} else if (msg.event === 'media') {
transcriptionService.send(msg.media.payload);
if (call && call.transcriptionService != null) {
call.transcriptionService.send(msg.media.payload);
}
} else if (msg.event === 'mark') {
const label = msg.mark.name;
console.log(`Twilio -> Audio completed mark (${msg.sequenceNumber}): ${label}`.red);
marks = marks.filter(m => m !== msg.mark.name);
if (call && call.marks) {
call.marks = call.marks.filter(m => m !== msg.mark.name);
}
} else if (msg.event === 'stop') {
console.log(`Twilio -> Media stream ${streamSid} ended.`.underline.red);

for (const k in Object.keys(activeCalls)) {
if (activeCalls[k] && activeCalls[k].callSid == callSid) {
delete activeCalls[k];
return;
}
}
}
});

transcriptionService.on('utterance', async (text) => {
// This is a bit of a hack to filter out empty utterances
if(marks.length > 0 && text?.length > 5) {
console.log('Twilio -> Interruption, Clearing stream'.red);
ws.send(
JSON.stringify({
streamSid,
event: 'clear',
})
);
}
});

transcriptionService.on('transcription', async (text) => {
if (!text) { return; }
console.log(`Interaction ${interactionCount} – STT -> GPT: ${text}`.yellow);
gptService.completion(text, interactionCount);
interactionCount += 1;
});

gptService.on('gptreply', async (gptReply, icount) => {
console.log(`Interaction ${icount}: GPT -> TTS: ${gptReply.partialResponse}`.green );
ttsService.generate(gptReply, icount);
});

ttsService.on('speech', (responseIndex, audio, label, icount) => {
console.log(`Interaction ${icount}: TTS -> TWILIO: ${label}`.blue);

streamService.buffer(responseIndex, audio);
});

streamService.on('audiosent', (markLabel) => {
marks.push(markLabel);
});
} catch (err) {
console.log(err);
}
Expand Down