-
Notifications
You must be signed in to change notification settings - Fork 98
fix: use web standard event apis for twilio websocket #127
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
base: main
Are you sure you want to change the base?
Changes from all commits
b6093c7
57868b5
0006b50
b2e29cb
cc04a29
a7278a2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
--- | ||
'@openai/agents': patch | ||
'@openai/agents-extensions': patch | ||
'@openai/agents-realtime': patch | ||
--- | ||
|
||
fix: use web standard event apis for twilio websocket |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,7 +7,13 @@ import { | |
RealtimeSessionConfig, | ||
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. My IDE autoformatted this file, but the changes are minimal, pointed out below |
||
} from '@openai/agents/realtime'; | ||
import { getLogger } from '@openai/agents'; | ||
import type { WebSocket, MessageEvent } from 'ws'; | ||
import type { | ||
WebSocket as NodeWebSocket, | ||
MessageEvent as NodeMessageEvent, | ||
ErrorEvent as NodeErrorEvent, | ||
} from 'ws'; | ||
|
||
import type { ErrorEvent } from 'undici-types'; | ||
Comment on lines
+10
to
+16
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. import some types |
||
|
||
/** | ||
* The options for the Twilio Realtime Transport Layer. | ||
|
@@ -18,7 +24,7 @@ export type TwilioRealtimeTransportLayerOptions = | |
* The websocket that is receiving messages from Twilio's Media Streams API. Typically the | ||
* connection gets passed into your request handler when running your WebSocket server. | ||
*/ | ||
twilioWebSocket: WebSocket; | ||
twilioWebSocket: WebSocket | NodeWebSocket; | ||
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. accept the websocket type |
||
}; | ||
|
||
/** | ||
|
@@ -48,7 +54,7 @@ export type TwilioRealtimeTransportLayerOptions = | |
* ``` | ||
*/ | ||
export class TwilioRealtimeTransportLayer extends OpenAIRealtimeWebSocket { | ||
#twilioWebSocket: WebSocket; | ||
#twilioWebSocket: WebSocket | NodeWebSocket; | ||
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. change this type here to accept |
||
#streamSid: string | null = null; | ||
#audioChunkCount: number = 0; | ||
#lastPlayedChunkCount: number = 0; | ||
|
@@ -82,74 +88,80 @@ export class TwilioRealtimeTransportLayer extends OpenAIRealtimeWebSocket { | |
options.initialSessionConfig, | ||
); | ||
// listen to Twilio messages as quickly as possible | ||
this.#twilioWebSocket.on('message', (message: MessageEvent) => { | ||
try { | ||
const data = JSON.parse(message.toString()); | ||
if (this.#logger.dontLogModelData) { | ||
this.#logger.debug('Twilio message:', data.event); | ||
} else { | ||
this.#logger.debug('Twilio message:', data); | ||
} | ||
this.emit('*', { | ||
type: 'twilio_message', | ||
message: data, | ||
}); | ||
switch (data.event) { | ||
case 'media': | ||
if (this.status === 'connected') { | ||
this.sendAudio(utils.base64ToArrayBuffer(data.media.payload)); | ||
} | ||
break; | ||
case 'mark': | ||
if ( | ||
!data.mark.name.startsWith('done:') && | ||
data.mark.name.includes(':') | ||
) { | ||
// keeping track of what the last chunk was that the user heard fully | ||
const count = Number(data.mark.name.split(':')[1]); | ||
if (Number.isFinite(count)) { | ||
this.#lastPlayedChunkCount = count; | ||
} else { | ||
this.#logger.warn( | ||
'Invalid mark name received:', | ||
data.mark.name, | ||
); | ||
this.#twilioWebSocket.addEventListener( | ||
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. change this to use .addEventListener |
||
'message', | ||
(message: MessageEvent | NodeMessageEvent) => { | ||
try { | ||
const data = JSON.parse(message.data.toString()); | ||
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. use message.data here |
||
if (this.#logger.dontLogModelData) { | ||
this.#logger.debug('Twilio message:', data.event); | ||
} else { | ||
this.#logger.debug('Twilio message:', data); | ||
} | ||
this.emit('*', { | ||
type: 'twilio_message', | ||
message: data, | ||
}); | ||
switch (data.event) { | ||
case 'media': | ||
if (this.status === 'connected') { | ||
this.sendAudio(utils.base64ToArrayBuffer(data.media.payload)); | ||
} | ||
} else if (data.mark.name.startsWith('done:')) { | ||
this.#lastPlayedChunkCount = 0; | ||
} | ||
break; | ||
case 'start': | ||
this.#streamSid = data.start.streamSid; | ||
break; | ||
default: | ||
break; | ||
break; | ||
case 'mark': | ||
if ( | ||
!data.mark.name.startsWith('done:') && | ||
data.mark.name.includes(':') | ||
) { | ||
// keeping track of what the last chunk was that the user heard fully | ||
const count = Number(data.mark.name.split(':')[1]); | ||
if (Number.isFinite(count)) { | ||
this.#lastPlayedChunkCount = count; | ||
} else { | ||
this.#logger.warn( | ||
'Invalid mark name received:', | ||
data.mark.name, | ||
); | ||
} | ||
} else if (data.mark.name.startsWith('done:')) { | ||
this.#lastPlayedChunkCount = 0; | ||
} | ||
break; | ||
case 'start': | ||
this.#streamSid = data.start.streamSid; | ||
break; | ||
default: | ||
break; | ||
} | ||
} catch (error) { | ||
this.#logger.error( | ||
'Error parsing message:', | ||
error, | ||
'Message:', | ||
message, | ||
); | ||
this.emit('error', { | ||
type: 'error', | ||
error, | ||
}); | ||
} | ||
} catch (error) { | ||
this.#logger.error( | ||
'Error parsing message:', | ||
error, | ||
'Message:', | ||
message, | ||
); | ||
}, | ||
); | ||
this.#twilioWebSocket.addEventListener('close', () => { | ||
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. change this to .addEventListener |
||
if (this.status !== 'disconnected') { | ||
this.close(); | ||
} | ||
}); | ||
this.#twilioWebSocket.addEventListener( | ||
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. change this to addEventListener |
||
'error', | ||
(error: ErrorEvent | NodeErrorEvent) => { | ||
this.emit('error', { | ||
type: 'error', | ||
error, | ||
}); | ||
} | ||
}); | ||
this.#twilioWebSocket.on('close', () => { | ||
if (this.status !== 'disconnected') { | ||
this.close(); | ||
} | ||
}); | ||
this.#twilioWebSocket.on('error', (error) => { | ||
this.emit('error', { | ||
type: 'error', | ||
error, | ||
}); | ||
this.close(); | ||
}); | ||
}, | ||
); | ||
this.on('audio_done', () => { | ||
this.#twilioWebSocket.send( | ||
JSON.stringify({ | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
import { | ||
isBrowserEnvironment, | ||
useWebSocketProtocols, | ||
WebSocket, | ||
} from '@openai/agents-realtime/_shims'; | ||
import { | ||
|
@@ -149,7 +150,8 @@ export class OpenAIRealtimeWebSocket | |
); | ||
} | ||
|
||
const websocketArguments = isBrowserEnvironment() | ||
// browsers and workerd should use the protocols argument, node should use the headers argument | ||
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. workerd's WebSocket constructor is "standards" based, so can't pass headers |
||
const websocketArguments = useWebSocketProtocols | ||
? [ | ||
'realtime', | ||
// Auth | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
export const WebSocket = globalThis.WebSocket; | ||
export function isBrowserEnvironment(): boolean { | ||
return false; | ||
} | ||
export const useWebSocketProtocols = true; | ||
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. open to some other name for this, but this seemed clear |
Uh oh!
There was an error while loading. Please reload this page.