Use GPT-Live via WebRTC

WebRTC supports browser-based or native client applications that need low-latency, real-time audio streaming with GPT-Live. Audio travels on a negotiated media track, and session events travel over a data channel.

For server-to-server integrations, see Use GPT-Live for real-time voice instead.

Prerequisites

  • An Azure subscription - Create one for free.
  • A Microsoft Foundry resource - Create a Microsoft Foundry resource.
  • A deployment of the gpt-live-1 model.
  • A trusted backend that holds your API key or Microsoft Entra ID credentials. GPT-Live doesn't support ephemeral client keys, so the browser never authenticates to the service directly.

How the WebRTC connection is established

GPT-Live doesn't issue ephemeral client keys, so the browser can't create a session directly. Session initialization goes through your trusted backend, while the audio media connects directly between the browser and the service:

  1. In the browser, create an RTCPeerConnection, add an audio transceiver and a data channel, and create an SDP offer.
  2. Send the SDP offer to your backend.
  3. Your backend forwards the offer to the service in a session-creation request, authenticated with your API key or Microsoft Entra ID credentials. The response contains the session ID and the SDP answer.
  4. Your backend relays the SDP answer to the browser.
  5. The browser applies the answer. Audio then flows directly between the browser and the service over the negotiated media track, and the data channel carries JSON events.

Browser: create the offer

const pc = new RTCPeerConnection();
pc.addTransceiver("audio", { direction: "sendrecv" });
const dataChannel = pc.createDataChannel("oai-events");

const offer = await pc.createOffer();
await pc.setLocalDescription(offer);

// Send offer.sdp to your backend and receive the SDP answer.
const answer = await fetch("/live/session", {
  method: "POST",
  headers: { "Content-Type": "application/sdp" },
  body: offer.sdp,
}).then((r) => r.text());

await pc.setRemoteDescription({ type: "answer", sdp: answer });

dataChannel.addEventListener("message", ({ data }) => {
  const event = JSON.parse(data);
  console.log(event.type, event);
});

Backend: create the session

Your backend sends the browser's SDP offer and the session configuration to the service, then returns the SDP answer to the browser. Keep credentials on the backend.

const response = await fetch("https://<your-resource-name>.openai.azure.com/openai/v1/live/sessions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    session: {
      model: "gpt-live-1",
      instructions: "Be concise.",
      delegation: { type: "client" },
    },
    transport: { type: "webrtc", sdp: offerSdp },
  }),
});

const { session, transport } = await response.json();
// Save session.id for sideband control; return transport.sdp (the answer) to the browser.

Save session.id if your backend attaches a sideband WebSocket to observe or steer the session.

Differences from the WebSocket transport

  • Don't send session.input_audio.append on the WebRTC data channel, and don't expect session.output_audio.delta there. Audio flows over the negotiated media track instead.
  • Input and output media are synchronized through RTP and don't carry JSON timing fields.
  • All other session events—session.update, the session.instructions.append / session.thinking.append / session.commentary.append context events, delegation events, transcripts, usage, and errors—use the same schema as WebSocket. See the GPT-Live event API reference.
  • Each WebRTC session has a minimum billable audio duration of 15 seconds. This minimum doesn't apply to WebSocket sessions.

Example code

The following example shows a basic frontend and backend implementation for using GPT-Live through WebRTC. To run the backend, you need Node.js.

In a new folder, create a Node.js project:

npm init -y

Install the required dependencies:

npm i express cors @azure/identity

Create the file server.js with the following contents:

import express from "express";
import cors from "cors";
import { DefaultAzureCredential } from "@azure/identity";

// Name of your Azure Foundry/OpenAI resource
const RESOURCE_NAME = "<your-resource-name>"
// Name of the GPT-Live Azure OpenAI deployment
const DEPLOYMENT_NAME = "<your-gpt-live-deployment-name>"
// Name of another Azure OpenAI deployment with responses support for delegation
const DELEGATION_DEPLOYMENT_NAME = "<your-responses-deployment-name>"

const credential = new DefaultAzureCredential();

// Creating express HTTP server 
const app = express();

// Enable CORS for all routes
// You should likely configure CORS more restrictively outside this development setup.
app.use(cors());

// Example endpoint for handling WebRTC SDP offers from the frontend
// You can wrap the SDP in JSON or Multipart form for passing additional data to your backend if needed.
app.post("/connect", express.text({ type: "application/sdp" }), async (req, res) => {
    const offerSdp = req.body;
    if (typeof offerSdp !== "string" || !offerSdp.trim()) {
        res.status(400).type("text/plain").send("An SDP offer is required.");
        return;
    }

    console.log("Received SDP offer on /connect");

    // Construct session options using our specified deployments
    const sessionOptions = {
        model: DEPLOYMENT_NAME,
        instructions: "Be concise.",
        delegation: {
            // This example uses responses delegation since client delegation requires additional logic
            type: "responses",
            responses: {
                model: DELEGATION_DEPLOYMENT_NAME
            }
        }
    };

    const token = await credential.getToken("https://cognitiveservices.azure.com/.default");
    const sessionResponse = await fetch(`https://${RESOURCE_NAME}.openai.azure.com/openai/v1/live/sessions`, {
        method: "POST",
        headers: {
            "Authorization": `Bearer ${token.token}`,
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            session: sessionOptions,
            transport: {
                type: "webrtc",
                sdp: offerSdp
            }
        })
    })
    
    if (!sessionResponse.ok) {
        throw new Error(`Realtime service request failed: ${sessionResponse.status}`);
    }
    // Example response:
    // {
    //     "session": {
    //         "id": "<session-id>"
    //     },
    //     "transport": {
    //         "type": "webrtc",
    //         "sdp": "<SDP-answer>"
    //     }
    // }
    const sessionData = await sessionResponse.json();

    if (typeof sessionData.transport?.sdp !== "string" || !sessionData.transport.sdp.trim()) {
        throw new Error("Realtime service returned no SDP answer.");
    }
    console.log(`Session created successfully, returning SDP answer. Session ID: ${sessionData.session.id}.`);
    res.type("application/sdp").send(sessionData.transport.sdp);

    // Your backend could now use the session ID to attach a sideband WebSocket client
    // The sideband can be used to receive events, steer the session, inject context or close the session as needed.
    // Open a WebSocket connection to wss://<RESOURCE_NAME>.openai.azure.com/openai/v1/live/sessions/<session-id>/attach with the same authorization header.
});

// Start the server on port 8080
app.listen(8080, () => {
    console.log("Backend is listening on Port 8080");
});

Start the backend by running:

node server.js

Create an additional file named frontend.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Azure OpenAI Live Audio</title>
        <style>
            body { max-width: 1200px; margin: 2rem auto; padding: 0 1rem; font-family: system-ui, sans-serif; }
            .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
            button { padding: 0.5rem 1rem; }
            .logs { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); gap: 1rem; }
            .log { height: 24rem; overflow: auto; border: 1px solid #ccc; padding: 0.75rem; background: #fafafa; }
            .log pre { margin: 0 0 0.75rem; white-space: pre-wrap; overflow-wrap: anywhere; }
        </style>
    </head>
    <body>
        <h1>Azure OpenAI Live Audio</h1>
        <div class="controls">
            <button id="startButton" onclick="StartSession()">Start Session</button>
            <button id="stopButton" disabled>Close Session</button>
            <audio id="remoteAudio" autoplay controls></audio>
        </div>
        <div class="logs">
            <section aria-labelledby="frontendLogHeading">
                <h2 id="frontendLogHeading">Frontend logs</h2>
                <div id="logContainer" class="log" role="log" aria-labelledby="frontendLogHeading" tabindex="0"></div>
            </section>
            <section aria-labelledby="dataChannelLogHeading">
                <h2 id="dataChannelLogHeading">Data channel messages</h2>
                <div id="dataChannelLog" class="log" role="log" aria-labelledby="dataChannelLogHeading" tabindex="0"></div>
            </section>
        </div>

        <script>
        async function StartSession() {
            const startButton = document.getElementById("startButton");
            const stopButton = document.getElementById("stopButton");
            const audioElement = document.getElementById("remoteAudio");
            let peerConnection;
            let clientMedia;
            let dataChannel;

            startButton.disabled = true;

            function stopSession() {
                if (dataChannel) dataChannel.close();
                if (peerConnection) peerConnection.close();
                if (clientMedia) clientMedia.getTracks().forEach(track => track.stop());
                audioElement.srcObject = null;
                stopButton.disabled = true;
                stopButton.onclick = null;
                startButton.disabled = false;
                logMessage("Session closed.");
            }

            try {
                logMessage("Requesting microphone access...");
                clientMedia = await navigator.mediaDevices.getUserMedia({ audio: true });
                peerConnection = new RTCPeerConnection();
                for (const track of clientMedia.getAudioTracks()) {
                    peerConnection.addTrack(track, clientMedia);
                }

                // Configure data channel with required name
                dataChannel = peerConnection.createDataChannel("oai-events");
                dataChannel.addEventListener("open", () => logMessage("Data channel opened."));
                dataChannel.addEventListener("close", () => logMessage("Data channel closed."));
                dataChannel.addEventListener("error", event => {
                    logMessage("Data channel error: " + event.error.message);
                });
                dataChannel.addEventListener("message", event => {
                    logDataChannelMessage("Incoming", event.data);
                });

                // Automatically play incoming audio tracks in audio element
                peerConnection.ontrack = (event) => {
                    audioElement.srcObject = event.streams[0] || new MediaStream([event.track]);
                    audioElement.play().catch(error => {
                        logMessage("Audio playback could not start: " + error.message +
                            ". Use the audio controls to play.");
                    });
                };

                peerConnection.onconnectionstatechange = () => {
                    logMessage("Connection state: " + peerConnection.connectionState);
                    if (peerConnection.connectionState === "failed") {
                        logMessage("WebRTC connection failed.");
                        stopSession();
                    }
                };

                const offer = await peerConnection.createOffer();
                await peerConnection.setLocalDescription(offer);

                // Wait for ICE gathering to complete, trickle ICE is not used in this example.
                if (peerConnection.iceGatheringState !== "complete") {
                    await new Promise(resolve => {
                        peerConnection.addEventListener("icegatheringstatechange", function onChange() {
                            if (peerConnection.iceGatheringState === "complete") {
                                peerConnection.removeEventListener("icegatheringstatechange", onChange);
                                resolve();
                            }
                        });
                    });
                }
                
                // Send SDP offer to our backend which owns authentication and session creation for the GPT-Live service
                logMessage("Exchanging SDP with /connect...");
                const response = await fetch("http://127.0.0.1:8080/connect", {
                    method: "POST",
                    headers: { "Content-Type": "application/sdp" },
                    body: peerConnection.localDescription.sdp
                });
                if (!response.ok) {
                    throw new Error("Connect request failed: " + response.status);
                }
                
                // Set the remote description with the SDP answer received from the backend
                await peerConnection.setRemoteDescription({
                    type: "answer",
                    sdp: await response.text()
                });
                stopButton.onclick = stopSession;
                stopButton.disabled = false;
                logMessage("SDP exchange complete. Speak into your microphone.");
            } catch (error) {
                console.error("Session failed:", error);
                logMessage("Session failed: " + error.message);
                stopSession();
            }
        }

        function logMessage(message) {
            appendLog("logContainer", message);
        }

        function logDataChannelMessage(direction, message) {
            appendLog("dataChannelLog", direction + ": " + message);
        }

        function sendDataChannelMessage(channel, message) {
            channel.send(message);
            logDataChannelMessage("Outgoing", message);
        }

        function appendLog(containerId, message) {
            const container = document.getElementById(containerId);
            const entry = document.createElement("pre");
            entry.textContent = "[" + new Date().toLocaleTimeString() + "] " + message;
            container.appendChild(entry);
            container.scrollTop = container.scrollHeight;
        }
        </script>
    </body>
</html>

Open this HTML file in the browser of your choice to start a GPT-Live session with interactive audio. In most cases, use WebRTC with a sideband WebSocket so the trusted backend can monitor and steer the session. The sideband can be connected after creating the session by opening a WebSocket connection to wss://<RESOURCE_NAME>.openai.azure.com/openai/v1/live/sessions/<session-id>/attach on the same resource.