1+ import { endpoints } from '$lib/services/api-endpoints.js' ;
2+ import { replaceUrl } from '$lib/helpers/http' ;
3+ import axios from 'axios' ;
4+
5+ export const llmRealtime = {
6+ /** @type {RTCPeerConnection } */
7+ pc : new RTCPeerConnection ( ) ,
8+ /** @param {string } agentId */
9+ async start ( agentId ) {
10+ const session = await initRealtimeSession ( agentId ) ;
11+ const EPHEMERAL_KEY = session . client_secret . value ;
12+
13+ this . pc = new RTCPeerConnection ( ) ;
14+
15+ // Set up to play remote audio from the model
16+ const audioEl = document . createElement ( "audio" ) ;
17+ audioEl . autoplay = true ;
18+ this . pc . ontrack = e => audioEl . srcObject = e . streams [ 0 ] ;
19+
20+ // Add local audio track for microphone input in the browser
21+ const ms = await navigator . mediaDevices . getUserMedia ( {
22+ audio : true
23+ } ) ;
24+ this . pc . addTrack ( ms . getTracks ( ) [ 0 ] ) ;
25+
26+ // Set up data channel for sending and receiving events
27+ const dc = this . pc . createDataChannel ( "oai-events" ) ;
28+ dc . addEventListener ( "message" , ( e ) => {
29+ // Realtime server events appear here!
30+ var data = JSON . parse ( e . data ) ;
31+ console . log ( data ) ;
32+ } ) ;
33+
34+ // Start the session using the Session Description Protocol (SDP)
35+ const offer = await this . pc . createOffer ( ) ;
36+ await this . pc . setLocalDescription ( offer ) ;
37+
38+ const baseUrl = "https://api.openai.com/v1/realtime" ;
39+ const sdpResponse = await fetch ( `${ baseUrl } ?model=${ session . model } ` , {
40+ method : "POST" ,
41+ body : offer . sdp ,
42+ headers : {
43+ Authorization : `Bearer ${ EPHEMERAL_KEY } ` ,
44+ "Content-Type" : "application/sdp"
45+ } ,
46+ } ) ;
47+
48+ /** @type {RTCSessionDescriptionInit } */
49+ const answer = {
50+ type : "answer" ,
51+ sdp : await sdpResponse . text ( ) ,
52+ } ;
53+ await this . pc . setRemoteDescription ( answer ) ;
54+ } ,
55+
56+ stop ( ) {
57+ // Stop the peer connection
58+ this . pc . close ( ) ;
59+ }
60+ }
61+
62+ /**
63+ * Execute agent realtime interaction
64+ * @param {string } agentId
65+ * @returns {Promise<import('$realtimeTypes').RealtimeSession> }
66+ */
67+ export async function initRealtimeSession ( agentId ) {
68+ let url = replaceUrl ( endpoints . agentInitRealtimeSessionUrl , { agentId : agentId } ) ;
69+ var response = await axios . get ( url ) ;
70+ return response . data ;
71+ }
0 commit comments