@@ -10,7 +10,7 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
1010
1111 // MARK: Subclass-provided endpoint constants
1212
13- override var defaultEndpoint : String { " https://api.openai.com/v1/realtime " }
13+ override var defaultEndpoint : String { " https://api.openai.com/v1/realtime/calls " }
1414 override var defaultModel : String { " gpt-realtime " }
1515
1616 // MARK: Chat-specific stored properties
@@ -41,6 +41,7 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
4141 let audioMixPlayer = AudioMixPlayer ( )
4242
4343 var toolDefinitions : [ [ String : Any ] ] = [ ]
44+ private var initialSessionConfiguration : [ String : Any ] ?
4445 lazy var eventHandler = WebRTCEventHandler ( )
4546
4647 // MARK: Init / deinit
@@ -69,7 +70,7 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
6970 // MARK: Virtual hook overrides
7071
7172 override func dataChannelDidOpen ( ) {
72- sendInitialSessionConfiguration ( )
73+ handleDataChannelOpenAfterInitialSessionSetup ( )
7374 }
7475
7576 override func handleDataChannelMessage ( _ event : [ String : Any ] ) {
@@ -220,17 +221,31 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
220221 attributes : logAttributes (
221222 for : . info ,
222223 metadata : [
223- " hasModel " : ( model ? . isEmpty == false ) ,
224- " hasBaseURL " : ( baseURL ? . isEmpty == false ) ,
224+ " resolvedModel " : resolvedModelName ( model ) ,
225+ " baseURL " : baseURL ?? " " ,
225226 " audioOutput " : audioOutput . rawValue ,
226227 " voice " : sessionVoice ,
227228 ] ) )
228229
229- let endpointURL = try buildEndpointURL ( baseURL : baseURL , model : model )
230+ let endpointURL = try buildEndpointURL (
231+ baseURL : baseURL ,
232+ model : model ,
233+ appendModelQuery : false
234+ )
230235 self . logger . log (
231236 " [VmWebrtc] Resolved OpenAI endpoint " ,
232237 attributes : logAttributes ( for : . debug , metadata : [ " endpoint " : endpointURL . absoluteString ] )
233238 )
239+ let sessionConfiguration = buildInitialRealtimeSessionConfiguration ( model : model )
240+ initialSessionConfiguration = sessionConfiguration
241+ self . logger . log (
242+ " [VmWebrtc] Prepared initial realtime session configuration " ,
243+ attributes : logAttributes (
244+ for : . debug ,
245+ metadata : [
246+ " session " : sessionConfiguration ,
247+ " sessionJSON " : prettyJSONString ( from : sessionConfiguration ) ?? " <invalid_session_json> " ,
248+ ] ) )
234249
235250 try configureAudioSession ( for : audioOutput )
236251 self . logger . log (
@@ -282,12 +297,26 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
282297 attributes : logAttributes ( for : . error ) )
283298 throw OpenAIWebRTCError . missingLocalDescription
284299 }
300+ self . logger . log (
301+ " [VmWebrtc] Final local SDP ready for OpenAI exchange " ,
302+ attributes : logAttributes (
303+ for : . debug ,
304+ metadata : [
305+ " endpoint " : endpointURL . absoluteString ,
306+ " sdpLength " : localSDP . count ,
307+ " sdpSummary " : analyzeSDP ( localSDP ) ,
308+ " sdp " : localSDP ,
309+ ] ) )
285310
286311 emitModuleEvent (
287312 " onVoiceSessionStatus " , payload : [ " status_update " : " Connecting to OpenAI endpoint... " ] )
288313
289- let answerSDP = try await exchangeSDPWithOpenAI (
290- apiKey : resolvedApiKey , endpointURL : endpointURL , offerSDP : localSDP )
314+ let answerSDP = try await exchangeRealtimeCallWithOpenAI (
315+ apiKey : resolvedApiKey ,
316+ endpointURL : endpointURL ,
317+ offerSDP : localSDP ,
318+ session : sessionConfiguration
319+ )
291320 let remoteDescription = RTCSessionDescription ( type : . answer , sdp : answerSDP )
292321 try await setRemoteDescription ( remoteDescription , for : connection )
293322 self . logger . log (
@@ -324,22 +353,19 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
324353 eventHandler . resetAudioStreamingState ( )
325354 eventHandler . resetFunctionCallState ( )
326355 eventHandler . shadowObserve_reset ( reason : " connection_closed " )
356+ initialSessionConfiguration = nil
327357
328358 return super . closeConnection ( )
329359 }
330360
331- // MARK: Session configuration (sent once data channel opens)
332-
333- func sendInitialSessionConfiguration ( ) {
334- guard ! hasSentInitialSessionConfig else { return }
361+ // MARK: Session configuration / startup
335362
336- guard let dataChannel , dataChannel . readyState == . open else {
337- self . logger . log (
338- " [VmWebrtc] Data channel not ready for initial session configuration " ,
339- attributes : logAttributes ( for : . warn , metadata : [ " hasChannel " : dataChannel != nil ] ) )
340- return
341- }
363+ private func resolvedModelName ( _ model : String ? ) -> String {
364+ let trimmedModel = model ? . trimmingCharacters ( in : . whitespacesAndNewlines ) ?? " "
365+ return trimmedModel . isEmpty ? defaultModel : trimmedModel
366+ }
342367
368+ private func buildInitialRealtimeSessionConfiguration ( model : String ? ) -> [ String : Any ] {
343369 let tools = buildTools ( )
344370
345371 if tools . isEmpty && ! toolDefinitions . isEmpty {
@@ -349,52 +375,79 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
349375 for : . warn , metadata : [ " definitionCount " : toolDefinitions . count ] ) )
350376 }
351377
352- var session : [ String : Any ] = [
353- " instructions " : sessionInstructions ,
354- " voice " : sessionVoice ,
355- " tools " : tools ,
356- ]
378+ var inputAudioConfig : [ String : Any ] = [ : ]
357379
358380 switch turnDetectionMode {
359381 case . semantic :
360- session [ " turn_detection " ] = [
382+ inputAudioConfig [ " turn_detection " ] = [
361383 " type " : " semantic_vad " ,
362384 " create_response " : true ,
363385 " eagerness " : " low " ,
364386 ]
365387 case . server :
366- session [ " turn_detection " ] = [
388+ inputAudioConfig [ " turn_detection " ] = [
367389 " type " : " server_vad " ,
368390 " create_response " : true ,
369391 ]
370392 }
371393
394+ if transcriptionEnabled {
395+ inputAudioConfig [ " transcription " ] = [ " model " : " whisper-1 " ]
396+ }
397+
398+ var audioConfig : [ String : Any ] = [
399+ " output " : [
400+ " voice " : sessionVoice ,
401+ ]
402+ ]
403+
404+ if ! inputAudioConfig . isEmpty {
405+ audioConfig [ " input " ] = inputAudioConfig
406+ }
407+
408+ var session : [ String : Any ] = [
409+ " type " : " realtime " ,
410+ " model " : resolvedModelName ( model ) ,
411+ " instructions " : sessionInstructions ,
412+ " audio " : audioConfig ,
413+ " tools " : tools ,
414+ ]
415+
372416 if let ratio = retentionRatio {
373417 session [ " truncation " ] = [
374418 " type " : " retention_ratio " ,
375419 " retention_ratio " : quantizedRetentionRatio ( ratio ) ,
376420 ]
377421 }
378422
379- if transcriptionEnabled {
380- session [ " input_audio_transcription " ] = [ " model " : " whisper-1 " ]
423+ return session
424+ }
425+
426+ func handleDataChannelOpenAfterInitialSessionSetup ( ) {
427+ guard ! hasSentInitialSessionConfig else { return }
428+
429+ guard let dataChannel , dataChannel . readyState == . open else {
430+ self . logger . log (
431+ " [VmWebrtc] Data channel not ready for initial session configuration " ,
432+ attributes : logAttributes ( for : . warn , metadata : [ " hasChannel " : dataChannel != nil ] ) )
433+ return
381434 }
382435
383- if let prettyData = try? JSONSerialization . data (
384- withJSONObject : session , options : [ . prettyPrinted ] ) ,
385- let prettyString = String ( data : prettyData , encoding : . utf8 )
386- {
436+ if let session = initialSessionConfiguration {
387437 self . logger . log (
388- " 📑 [VmWebrtc] Sending session.update payload " ,
389- attributes : logAttributes ( for : . debug , metadata : [ " session " : prettyString ] ) )
438+ " 📑 [VmWebrtc] Initial session already configured via /v1/realtime/calls " ,
439+ attributes : logAttributes (
440+ for : . debug ,
441+ metadata : [
442+ " session " : session ,
443+ " sessionJSON " : prettyJSONString ( from : session ) ?? " <invalid_session_json> " ,
444+ ] ) )
390445 } else {
391446 self . logger . log (
392- " 📑 [VmWebrtc] Sending session.update payload (fallback formatting) " ,
393- attributes : logAttributes ( for : . debug , metadata : [ " session " : session ] ) )
447+ " [VmWebrtc] Missing cached initial session configuration when data channel opened " ,
448+ attributes : logAttributes ( for : . warn ) )
394449 }
395450
396- _ = sendEvent ( [ " type " : " session.update " , " session " : session ] )
397-
398451 Task { @MainActor in
399452 self . emitModuleEvent (
400453 " onVoiceSessionStatus " , payload : [ " status_update " : " Started Voice Session " ] )
0 commit comments