|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | + <head> |
| 4 | + <meta charset="UTF-8" /> |
| 5 | + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
| 6 | + <title>Azure OpenAI Realtime Session</title> |
| 7 | + </head> |
| 8 | + <body> |
| 9 | + <h1>Azure OpenAI Realtime Session</h1> |
| 10 | + <p> |
| 11 | + WARNING: Don't use this code sample in production with the API key |
| 12 | + hardcoded. Use a protected backend service to call the sessions API and |
| 13 | + generate the ephemeral key. Then return the ephemeral key to the client. |
| 14 | + </p> |
| 15 | + <button onclick="StartSession()">Start Session</button> |
| 16 | + |
| 17 | + <!-- Log container for API messages --> |
| 18 | + <div id="logContainer"></div> |
| 19 | + |
| 20 | + <script> |
| 21 | + // The following constants are rendered from a Jinja2 template at runtime. |
| 22 | + // They must be valid JavaScript string literals (the CLI will json-encode them). |
| 23 | + const WEBRTC_URL = {{ WEBRTC_URL }}; |
| 24 | + |
| 25 | + // The SESSIONS_URL includes the Azure OpenAI resource URL, |
| 26 | + // deployment name, the /realtime/sessions path, and the API version. |
| 27 | + // The Azure OpenAI resource region isn't part of the SESSIONS_URL. |
| 28 | + const SESSIONS_URL = {{ SESSIONS_URL }}; |
| 29 | + |
| 30 | + // The API key of the Azure OpenAI resource. WARNING: do not expose this in |
| 31 | + // production. Use an ephemeral key instead. |
| 32 | + const API_KEY = {{ API_KEY }}; |
| 33 | + |
| 34 | + // The deployment name might not be the same as the model name. |
| 35 | + const DEPLOYMENT = {{ DEPLOYMENT }}; |
| 36 | + const VOICE = {{ VOICE }}; |
| 37 | + |
| 38 | + async function StartSession() { |
| 39 | + try { |
| 40 | + // WARNING: Don't use this code sample in production |
| 41 | + // with the API key hardcoded. |
| 42 | + // Use a protected backend service to call the |
| 43 | + // sessions API and generate the ephemeral key. |
| 44 | + // Then return the ephemeral key to the client. |
| 45 | + |
| 46 | + const response = await fetch(SESSIONS_URL, { |
| 47 | + method: "POST", |
| 48 | + headers: { |
| 49 | + //"Authorization": `Bearer ${ACCESS_TOKEN}`, |
| 50 | + "api-key": API_KEY, |
| 51 | + "Content-Type": "application/json", |
| 52 | + }, |
| 53 | + body: JSON.stringify({ |
| 54 | + model: DEPLOYMENT, |
| 55 | + voice: VOICE, |
| 56 | + }), |
| 57 | + }); |
| 58 | + |
| 59 | + if (!response.ok) { |
| 60 | + throw new Error(`API request failed`); |
| 61 | + } |
| 62 | + |
| 63 | + const data = await response.json(); |
| 64 | + |
| 65 | + const sessionId = data.id; |
| 66 | + const ephemeralKey = data.client_secret?.value; |
| 67 | + console.error("Ephemeral key:", ephemeralKey); |
| 68 | + |
| 69 | + // Mask the ephemeral key in the log message. |
| 70 | + logMessage("Ephemeral Key Received: " + "***"); |
| 71 | + logMessage("WebRTC Session Id = " + sessionId); |
| 72 | + |
| 73 | + // Set up the WebRTC connection using the ephemeral key. |
| 74 | + init(ephemeralKey); |
| 75 | + } catch (error) { |
| 76 | + console.error("Error fetching ephemeral key:", error); |
| 77 | + logMessage("Error fetching ephemeral key: " + error.message); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + async function init(ephemeralKey) { |
| 82 | + let peerConnection = new RTCPeerConnection(); |
| 83 | + |
| 84 | + // Set up to play remote audio from the model. |
| 85 | + const audioElement = document.createElement("audio"); |
| 86 | + audioElement.autoplay = true; |
| 87 | + document.body.appendChild(audioElement); |
| 88 | + |
| 89 | + peerConnection.ontrack = (event) => { |
| 90 | + audioElement.srcObject = event.streams[0]; |
| 91 | + }; |
| 92 | + |
| 93 | + // Set up data channel for sending and receiving events |
| 94 | + const clientMedia = await navigator.mediaDevices.getUserMedia({ |
| 95 | + audio: true, |
| 96 | + }); |
| 97 | + const audioTrack = clientMedia.getAudioTracks()[0]; |
| 98 | + peerConnection.addTrack(audioTrack); |
| 99 | + |
| 100 | + const dataChannel = |
| 101 | + peerConnection.createDataChannel("realtime-channel"); |
| 102 | + |
| 103 | + dataChannel.addEventListener("open", () => { |
| 104 | + logMessage("Data channel is open"); |
| 105 | + updateSession(dataChannel); |
| 106 | + }); |
| 107 | + |
| 108 | + dataChannel.addEventListener("message", (event) => { |
| 109 | + const realtimeEvent = JSON.parse(event.data); |
| 110 | + console.log(realtimeEvent); |
| 111 | + logMessage( |
| 112 | + "Received server event: " + JSON.stringify(realtimeEvent, null, 2) |
| 113 | + ); |
| 114 | + if (realtimeEvent.type === "session.update") { |
| 115 | + const instructions = realtimeEvent.session.instructions; |
| 116 | + logMessage("Instructions: " + instructions); |
| 117 | + } else if (realtimeEvent.type === "session.error") { |
| 118 | + logMessage("Error: " + realtimeEvent.error.message); |
| 119 | + } else if (realtimeEvent.type === "session.end") { |
| 120 | + logMessage("Session ended."); |
| 121 | + } |
| 122 | + }); |
| 123 | + |
| 124 | + dataChannel.addEventListener("close", () => { |
| 125 | + logMessage("Data channel is closed"); |
| 126 | + }); |
| 127 | + |
| 128 | + // Start the session using the Session Description Protocol (SDP) |
| 129 | + const offer = await peerConnection.createOffer(); |
| 130 | + await peerConnection.setLocalDescription(offer); |
| 131 | + |
| 132 | + const sdpResponse = await fetch(`${WEBRTC_URL}?model=${DEPLOYMENT}`, { |
| 133 | + method: "POST", |
| 134 | + body: offer.sdp, |
| 135 | + headers: { |
| 136 | + Authorization: `Bearer ${ephemeralKey}`, |
| 137 | + "Content-Type": "application/sdp", |
| 138 | + }, |
| 139 | + }); |
| 140 | + |
| 141 | + const answer = { type: "answer", sdp: await sdpResponse.text() }; |
| 142 | + await peerConnection.setRemoteDescription(answer); |
| 143 | + |
| 144 | + const button = document.createElement("button"); |
| 145 | + button.innerText = "Close Session"; |
| 146 | + button.onclick = stopSession; |
| 147 | + document.body.appendChild(button); |
| 148 | + |
| 149 | + // Send a client event to update the session |
| 150 | + function updateSession(dataChannel) { |
| 151 | + const event = { |
| 152 | + type: "session.update", |
| 153 | + session: { |
| 154 | + instructions: |
| 155 | + "You are a helpful AI assistant responding in natural, engaging language.", |
| 156 | + }, |
| 157 | + }; |
| 158 | + dataChannel.send(JSON.stringify(event)); |
| 159 | + logMessage("Sent client event: " + JSON.stringify(event, null, 2)); |
| 160 | + } |
| 161 | + |
| 162 | + function stopSession() { |
| 163 | + if (dataChannel) dataChannel.close(); |
| 164 | + if (peerConnection) peerConnection.close(); |
| 165 | + peerConnection = null; |
| 166 | + logMessage("Session closed."); |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + function logMessage(message) { |
| 171 | + const logContainer = document.getElementById("logContainer"); |
| 172 | + const p = document.createElement("p"); |
| 173 | + p.textContent = message; |
| 174 | + logContainer.appendChild(p); |
| 175 | + } |
| 176 | + </script> |
| 177 | + </body> |
| 178 | +</html> |
0 commit comments