How do you use WebRTC instead of WebSockets for low-latency browser-to-LLM voice conversations? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you use WebRTC instead of WebSockets for low-latency browser-to-LLM voice conversations?

message-square
0

Overview

WebRTC uses UDP media transport with built-in jitter buffers, packet-loss recovery, and acoustic echo cancellation. On Wi-Fi or mobile networks, TCP-based WebSockets can stall when a packet drops, while WebRTC keeps voice smooth.

  • Media over WebRTC, control events over DataChannel: Stream raw microphone and reply audio tracks over RTCPeerConnection and send JSON control events over an RTCDataChannel.
  • Short-lived session tokens on the server: Mint ephemeral client credentials on your Node.js/TypeScript backend so your main LLM API key never reaches the browser.

Steps

  1. Mint a short-lived client token on the server: Call your backend or provider client-secrets endpoint with your secret API key and return only a temporary token to the browser.
  2. Capture microphone audio and create RTCPeerConnection: Enable browser echo cancellation and noise suppression, add the audio track, and attach a data channel for session and tool events.
  3. Exchange SDP offer and answer: Send the browser’s SDP offer to the realtime WebRTC endpoint and apply the returned SDP answer to start media flow.
  4. Handle barge-in and clean teardown: Stop local playback when the user speaks over the model, and close tracks and peer connections on hangup.

Example

import express from "express";

// --- Server: Mint short-lived client token (Node.js / TypeScript) ---
export function createVoiceTokenRouter(openAiApiKey: string) {
  const router = express.Router();

  router.post("/api/voice/session", async (_req, res) => {
    try {
      const response = await fetch("[https://api.openai.com/v1/realtime/client_secrets](https://api.openai.com/v1/realtime/client_secrets)", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${openAiApiKey}`, "Content-Type": "application/json", }, body: JSON.stringify({ session: { type: "realtime", model: "gpt-realtime-2.1", }, }), });  if (!response.ok) { const text = await response.text(); res.status(response.status).json({ error: text }); return; }  const data = (await response.json()) as { value?: string; client_secret?: { value?: string } }; const token = data.value ?? data.client_secret?.value; res.json({ token }); } catch (err) { res.status(500).json({ error: err instanceof Error ? err.message : "Token error" }); } });  return router; }  // --- Browser: Connect mic and audio playback over WebRTC --- export class BrowserVoiceWebRtcClient { private pc: RTCPeerConnection \vert{} null = null; private dc: RTCDataChannel \vert{} null = null; private localStream: MediaStream \vert{} null = null;  async connect(audioElement: HTMLAudioElement, onEvent?: (evt: unknown) => void): Promise<void> { const tokenRes = await fetch("/api/voice/session", { method: "POST" }); if (!tokenRes.ok) { throw new Error("Failed to fetch ephemeral voice token."); } const { token } = (await tokenRes.json()) as { token: string };  const pc = new RTCPeerConnection(); this.pc = pc;  audioElement.autoplay = true; pc.ontrack = (event) => { const [remoteStream] = event.streams; if (remoteStream) { audioElement.srcObject = remoteStream; } };  const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, }, }); this.localStream = stream;  for (const track of stream.getAudioTracks()) { pc.addTrack(track, stream); }  const dc = pc.createDataChannel("oai-events"); this.dc = dc;  dc.onopen = () => { dc.send( JSON.stringify({ type: "session.update", session: { type: "realtime", instructions: "Keep answers short, clear, and spoken naturally.", }, }) ); };  dc.onmessage = (event) => { try { const parsed = JSON.parse(String(event.data)); onEvent?.(parsed); } catch { // Ignore non-JSON control frames } };  const offer = await pc.createOffer(); await pc.setLocalDescription(offer);  const sdpResponse = await fetch("[https://api.openai.com/v1/realtime/calls](https://api.openai.com/v1/realtime/calls)", { method: "POST", headers: { Authorization: `Bearer ${token}`,
        "Content-Type": "application/sdp",
      },
      body: offer.sdp,
    });

    if (!sdpResponse.ok) {
      throw new Error(`SDP exchange failed: \${sdpResponse.status}`);
    }

    const answerSdp = await sdpResponse.text();
    await pc.setRemoteDescription({ type: "answer", sdp: answerSdp });
  }

  sendEvent(payload: Record<string, unknown>): void {
    if (this.dc && this.dc.readyState === "open") {
      this.dc.send(JSON.stringify(payload));
    }
  }

  disconnect(): void {
    this.dc?.close();
    this.dc = null;

    this.localStream?.getTracks().forEach((t) => t.stop());
    this.localStream = null;

    this.pc?.close();
    this.pc = null;
  }
}

Tips

  • Use HTTPS or localhost: Browsers block microphone access (getUserMedia) on plain HTTP origins outside localhost.
  • Set voice before audio starts: Lock your chosen voice in session setup before the first audio reply plays.
  • Use WebSockets for server-to-server or phone bridges: Keep WebSockets for backend pipelines or SIP/telephony bridges where your server owns the audio stream.