-
Notifications
You must be signed in to change notification settings - Fork 157
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
kevinmershon
wants to merge
2
commits into
twilio-labs:main
Choose a base branch
from
kevinmershon:bugfix-twilio-stream-restart-fix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Fix the issue of Twilio sometimes starting a new websocket connection for the same call concurrently #61
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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) => { | ||
// 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]) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
} | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.