Use the GPT Realtime API via WebRTC

Azure OpenAI GPT Realtime API for speech and audio offers access to models which support low-latency, "speech in, speech out" conversational interactions, translations or transcriptions.

You can use the Realtime API via WebRTC, SIP, or WebSocket to send audio input to the model and receive audio responses in real time.

In most cases, use the WebRTC API for real-time audio streaming directly to the user. The WebRTC API is a web standard that enables real-time communication (RTC) between browsers, mobile applications and services like Realtime API. Here are some reasons why WebRTC is preferred for real-time audio streaming:

  • Low latency: WebRTC is designed to minimize delay, making it suitable for audio and video communication where low latency is critical for maintaining quality and synchronization.
  • Media handling: WebRTC has built-in support for audio and video codecs, providing optimized handling of media streams.
  • Error correction: WebRTC includes mechanisms for handling packet loss and jitter, which are essential for maintaining the quality of audio streams over unpredictable networks.
  • Direct media transmission: WebRTC allows media packets to flow directly between Azure and the user, without the need to forward them through your own backend. Your backend only handles session setup and authentication, as well as the optional sideband.

Use the Realtime API via WebSockets if you need to:

  • Start a server-to-server Realtime API session
  • Input audio faster than realtime
  • Modify the output audio or event data before fowarding it to the user

Please see Realtime API for speech and audio for a general overview on Realtime API, including a list of supported models and protocols.

Prerequisites

Before you can use GPT real-time audio, you need:

Realtime API WebRTC flows

There is two ways for a backend to create and set up a Realtime API WebRTC session. Depending on the amount of control the backend should have over session setup, you can pick one of the following designs:

Design Description Advantages
Ephemeral token backend The backend is responsible for authenticating the request and providing an ephemeral token. The ephemeral token is used by the client to open a session with Realtime API. Simple to implement, no WebRTC knowledge necessary.
Session proxy backend The backend receives the browsers WebRTC SDP Offer and uses it to create a Realtime API session. It then returns the SDP Answer to the frontend to open the direct WebRTC connection. Control over event filters and entire authentication flow, possibly lower setup latency.

Ephemeral token example

The Express server uses Microsoft Entra ID to create a short-lived token at /openai/v1/realtime/client_secrets. The browser uses that token to exchange its Session Description Protocol (SDP) offer for an answer directly with Azure OpenAI.

Use Node.js 22 or later, the Azure CLI, and a browser with microphone access. In an empty directory, run npm install express@5 @azure/identity, then run az login. Set AZURE_OPENAI_ENDPOINT to https://<resource-name>.openai.azure.com and AZURE_OPENAI_DEPLOYMENT to your realtime model deployment name.

Save this code as server.mjs:

import { fileURLToPath } from "node:url";
import { DefaultAzureCredential } from "@azure/identity";
import express from "express";

const app = express();
const credential = new DefaultAzureCredential();
const endpoint = process.env.AZURE_OPENAI_ENDPOINT?.replace(/\/+$/, "");
const model = process.env.AZURE_OPENAI_DEPLOYMENT;
if (!endpoint || !model) {
  throw new Error("Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_DEPLOYMENT.");
}

app.get("/", (req, res) => {
  res.sendFile("index.html", {
    root: fileURLToPath(new URL(".", import.meta.url)),
  });
});

app.post("/token", async (req, res) => {
  // Use Entra ID to mint a short-lived token for the browser.
  const { token } = await credential.getToken("https://ai.azure.com/.default");
  const url = `${endpoint}/openai/v1/realtime`;
  const response = await fetch(`${url}/client_secrets`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ session: { type: "realtime", model } }),
  });
  if (!response.ok) {
    throw new Error(`Token request failed: HTTP ${response.status}`);
  }
  const { value } = await response.json();
  if (!value) throw new Error("The token response is missing its value.");
  res.set("Cache-Control", "no-store")
    .json({ token: value, callsUrl: `${url}/calls` });
});

app.listen(3000, "127.0.0.1");

Save this page as index.html in the same directory:

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Realtime API: ephemeral token</title>
<button id="start">Start session</button>
<p id="status" role="status"></p>
<audio id="output" autoplay controls></audio>
<script>
  const start = document.querySelector("#start");
  const status = document.querySelector("#status");
  const output = document.querySelector("#output");

  start.onclick = async () => {
    start.disabled = true;
    status.textContent = "Connecting...";
    const peer = new RTCPeerConnection();
    let mic;
    try {
      mic = await navigator.mediaDevices.getUserMedia({ audio: true });
      peer.addTrack(mic.getAudioTracks()[0], mic);
      peer.ontrack = ({ streams }) => { output.srcObject = streams[0]; };
      const events = peer.createDataChannel("oai-events");
      events.onopen = () => { status.textContent = "Connected. Speak now."; };
      events.onmessage = ({ data }) => {
        console.log("Realtime event:", JSON.parse(data));
      };

      // Exchange SDP directly with Azure OpenAI.
      await peer.setLocalDescription(await peer.createOffer());
      const secret = await fetch("/token", { method: "POST" });
      if (!secret.ok) throw new Error(`Token request failed: ${secret.status}`);
      const { token, callsUrl } = await secret.json();
      const answer = await fetch(callsUrl, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/sdp",
        },
        body: peer.localDescription.sdp,
      });
      if (!answer.ok) throw new Error(`SDP exchange failed: ${answer.status}`);
      await peer.setRemoteDescription({ type: "answer", sdp: await answer.text() });
    } catch (error) {
      peer.close();
      mic?.getTracks().forEach(track => track.stop());
      status.textContent = error.message;
      start.disabled = false;
    }
  };
</script>
</html>

Run node server.mjs and open http://127.0.0.1:3000. Select Start session, grant microphone access, and speak when the page shows Connected. Speak now. You hear the model's response. Close the tab to end the session.

Open your browser's developer tools and select Console to see the full contents of incoming data channel messages.

Reference: DefaultAzureCredential, Realtime API events.

Session proxy example

The browser sends its SDP offer to Express and receives only the SDP answer. Azure OpenAI requires an ephemeral token for /openai/v1/realtime/calls, so the proxy uses Microsoft Entra ID to create one and keeps it on the server. Audio flows directly between the browser and Azure OpenAI.

Set webrtcfilter on the Azure OpenAI /calls request to control which messages pass through the WebRTC data channel. The filter doesn't affect the RTP audio stream.

webrtcfilter Azure OpenAI to browser Browser to Azure OpenAI
off (default) No filtering. No filtering.
on Allows only input_audio_buffer.speech_started, input_audio_buffer.speech_stopped, output_audio_buffer.started, output_audio_buffer.stopped, conversation.item.input_audio_transcription.completed, conversation.item.added, conversation.item.created, response.text.delta, response.text.done, response.audio_transcript.delta, response.audio_transcript.done, response.output_text.delta, response.output_text.done, response.output_audio_transcript.delta, and response.output_audio_transcript.done. No filtering.
v2 Allows only input_audio_buffer.speech_started, input_audio_buffer.speech_stopped, input_audio_buffer.committed, input_audio_buffer.timeout_triggered, output_audio_buffer.started, output_audio_buffer.stopped, conversation.item.input_audio_transcription.completed, conversation.item.input_audio_transcription.failed, conversation.item.truncated, conversation.item.added, conversation.item.done, response.output_audio_transcript.delta, response.output_audio_transcript.done, response.content_part.added, response.output_item.added, mcp_list_tools.completed, and mcp_list_tools.failed. No filtering.
v3 Uses the v2 allowlist, but also drops conversation.item.added when item.type is message and item.role is system. Allows only input_audio_buffer.append, input_audio_buffer.commit, input_audio_buffer.clear, output_audio_buffer.clear, and response.cancel.

All enabled modes drop unlisted server events, including error, session.created, session.updated, and response.done. In v3, Azure OpenAI also drops unlisted client messages, including session.update, response.create, and malformed or untyped messages. The following example will use the v3 filter.

Use the same dependencies and environment variables as the ephemeral token example. Stop the first server if it's running. Save this code as server.mjs:

import { fileURLToPath } from "node:url";
import { DefaultAzureCredential } from "@azure/identity";
import express from "express";

const app = express();
const credential = new DefaultAzureCredential();
const endpoint = process.env.AZURE_OPENAI_ENDPOINT?.replace(/\/+$/, "");
const model = process.env.AZURE_OPENAI_DEPLOYMENT;
if (!endpoint || !model) {
  throw new Error("Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_DEPLOYMENT.");
}

app.get("/", (req, res) => {
  res.sendFile("index.html", {
    root: fileURLToPath(new URL(".", import.meta.url)),
  });
});

app.post("/connect", express.text({ type: "application/sdp" }), async (req, res) => {
  if (!req.body) {
    res.status(400).send("Send an SDP offer with Content-Type: application/sdp.");
    return;
  }
  const { token } = await credential.getToken("https://ai.azure.com/.default");
  const url = `${endpoint}/openai/v1/realtime`;
  const secret = await fetch(`${url}/client_secrets`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ session: { type: "realtime", model } }),
  });
  if (!secret.ok) throw new Error(`Token request failed: HTTP ${secret.status}`);
  const { value } = await secret.json();
  if (!value) throw new Error("The token response is missing its value.");

  // Exchange SDP on the server so the token stays here.
  const answer = await fetch(`${url}/calls?webrtcfilter=v3`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${value}`,
      "Content-Type": "application/sdp",
    },
    body: req.body,
  });
  if (!answer.ok) throw new Error(`SDP exchange failed: HTTP ${answer.status}`);
  res.type("application/sdp").send(await answer.text());
});

app.listen(3000, "127.0.0.1");

Save this page as index.html next to the proxy server:

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Realtime API: session proxy</title>
<button id="start">Start session</button>
<p id="status" role="status"></p>
<audio id="output" autoplay controls></audio>
<script>
  const start = document.querySelector("#start");
  const status = document.querySelector("#status");
  const output = document.querySelector("#output");

  start.onclick = async () => {
    start.disabled = true;
    status.textContent = "Connecting...";
    const peer = new RTCPeerConnection();
    let mic;
    try {
      mic = await navigator.mediaDevices.getUserMedia({ audio: true });
      peer.addTrack(mic.getAudioTracks()[0], mic);
      peer.ontrack = ({ streams }) => { output.srcObject = streams[0]; };
      const events = peer.createDataChannel("oai-events");
      events.onopen = () => { status.textContent = "Connected. Speak now."; };
      events.onmessage = ({ data }) => {
        console.log("Realtime event:", JSON.parse(data));
      };

      // Send SDP through the proxy; audio stays peer-to-peer.
      await peer.setLocalDescription(await peer.createOffer());
      const answer = await fetch("/connect", {
        method: "POST",
        headers: { "Content-Type": "application/sdp" },
        body: peer.localDescription.sdp,
      });
      if (!answer.ok) throw new Error(`SDP exchange failed: ${answer.status}`);
      await peer.setRemoteDescription({ type: "answer", sdp: await answer.text() });
    } catch (error) {
      peer.close();
      mic?.getTracks().forEach(track => track.stop());
      status.textContent = error.message;
      start.disabled = false;
    }
  };
</script>
</html>

Run node server.mjs and open http://127.0.0.1:3000. Start a session and speak to hear a response. Open your browser's developer tools and select Console to see the full contents of incoming data channel messages that pass the filter, such as input_audio_buffer.speech_started and response.output_audio_transcript.done.

Reference: DefaultAzureCredential, Realtime API events.

WebSocket sideband and observer

Attach a server-side WebSocket after the /calls request opens the session and returns a Location header. Use the last path segment as call_id to target the open session. A sideband connection lets your server observe events or change session settings while the browser handles audio.

The webrtcfilter parameter affects only the WebRTC data channel, not the sideband WebSocket. However, the sideband does not receive messages containing input or output audio data. The audio itself travels over the WebRTC media connection.

Run npm install ws and add import WebSocket from "ws"; to the proxy server imports. In the /connect handler, replace the res.type(...).send(...) line with this code:

const location = answer.headers.get("location");
if (!location) throw new Error("The calls response is missing Location.");

// Target the existing call instead of opening a new session.
const callId = new URL(location, endpoint).pathname.split("/").at(-1);
const sidebandUrl = new URL("/openai/v1/realtime", endpoint);
sidebandUrl.protocol = "wss:";
sidebandUrl.searchParams.set("call_id", callId);

res.type("application/sdp").send(await answer.text());

const sideband = new WebSocket(sidebandUrl, {
  headers: { Authorization: `Bearer ${token}` },
});
sideband.on("error", error => console.error("Sideband:", error.message));
sideband.on("message", data => {
  const event = JSON.parse(data.toString());
  if (event.type === "session.updated") {
    console.log("Sideband:", event.type, event.session.id);
  } else {
    console.log("Sideband:", event.type);
  }
  if (event.type === "error") console.error(event.error.message);
});
sideband.on("open", () => {
  sideband.send(JSON.stringify({
    type: "session.update",
    session: { type: "realtime", instructions: "Keep replies brief." },
  }));
});

Reference: Realtime session configuration.

Troubleshooting

Firewall

If a firewall restricts outbound traffic from the client, allow the following traffic for the Realtime API:

Port Protocols Destination
3478 UDP, TCP The regional AzureCloud.<region> service tag for your Azure OpenAI resource, such as AzureCloud.eastus2. See the list of Azure IP ranges and service tags.

Authentication errors

  • 401 Unauthorized: Verify that your API key or Microsoft Entra ID token is valid. For Microsoft Entra ID, check that the identity has the Cognitive Services User role on the Azure OpenAI resource.
  • 403 Forbidden: Check that your resource is in a region that supports your model. See Region availability for Foundry Models sold by Azure.

Connection errors

  • WebRTC connection failed: Check that your browser supports WebRTC and that the page has microphone access. Use HTTPS or a loopback address for local testing. If a firewall restricts outbound traffic, check the firewall rule.
  • Data channel doesn't open: Check the browser console for ICE connection state errors and verify that the ephemeral token hasn't expired.
  • SDP exchange failed: Verify that the /calls URL is correct and that the ephemeral token is valid.

Model errors

  • Model not found: Check that the deployment name matches exactly, including capitalization, and that you deployed a supported realtime model.
  • Quota exceeded: Check the Azure OpenAI quota in the Azure portal. The Realtime API has a separate quota from chat completions.

Audio issues

  • No audio output: Check that the audio element has the autoplay attribute and that the browser allows playback. If autoplay is blocked, select Play in the audio controls.
  • Poor audio quality: Check your network connection and try reducing other network traffic. WebRTC adapts to changing network conditions.