AGTCloud API Docs
GuidesAPI ReferenceIntegrations and resourcesUpdate and help
RealtimeGPT-Live Realtime Voice

Create a WebRTC session

Submit session configuration and an SDP Offer to create a realtime voice media connection.

Submit the complete client-generated SDP Offer and use the returned SDP Answer for media negotiation. Audio tracks carry speech; the DataChannel exchanges JSON events.

POST/v1/live/sessions

Submit the session configuration and complete SDP Offer to receive a session ID and SDP Answer. After setting the remote SDP, wait for session.started; do not send session.start again.

Authorization

bearerAuth
AuthorizationBearer <token>

Platform API Key.

In: header

Request Body

application/json

TypeScript Definitions

Use the request body type in TypeScript.

Response Body

application/json

application/json

application/json

Establish the media connection

  1. On an HTTPS page or localhost, request microphone permission and create an RTCPeerConnection.
  2. Add an audio track and create a DataChannel, then generate an Offer, set the local SDP, and wait for ICE gathering to complete.
  3. Submit the session configuration and SDP Offer through your application backend, save the returned session.id, and set the SDP Answer as the remote description.
  4. Begin application control after receiving session.started on the DataChannel. HTTP creation already starts the session; do not send session.start again.

Try It submits the create request; it does not request microphone access or establish audio tracks automatically. The SDP must come from this client connection; the response SDP below illustrates field structure only.

Control channels and standby

ConfigurationUsage
Media encodingNegotiated through SDP. Do not pass audio.format or send primary PCM/Base64 audio through the DataChannel
Frontend event permissionsclient.data_channel restricts only the DataChannel, not trusted server attach. An empty event array does not close audio tracks
Background controlThe DataChannel does not expose session.update or response.create. Use WebRTC server control
Voice wake-upwake_policy.type: "speech"; vad_threshold ranges from 0 to 1, default 0.5, for initial activation and wake-up after standby
Automatic standbyidle_timeout_s is an integer from 5 to 60 seconds. Pauses after no input or output transcripts for that duration; keep the microphone track active for wake-up

Browser and backend examples

Browser code calls your own /api/session for the create result. Keep the API Key only in the Node.js backend's API_KEY environment variable. The backend example requires express; place browser code in its public directory and call startLive(audioElement, onEvent) from a button click. Pass the audio element to play the remote track. The returned object's close() ends the session.

WebRTCWebRTC connection examples
// Call after the user clicks Start; include <audio id="reply" autoplay playsinline> on the page.
export async function startLive(audioElement, onEvent = console.log) {
  const pc = new RTCPeerConnection();
  const dc = pc.createDataChannel('oai-events');
  let mic, sessionId, finalEvent;
  let resolveStarted, resolveClosed;
  const started = new Promise(resolve => { resolveStarted = resolve; });
  const closed = new Promise(resolve => { resolveClosed = resolve; });
  const bounded = async (promise, ms) => {
    let timer;
    try { return await Promise.race([promise, new Promise((_, reject) => {
      timer = setTimeout(() => reject(new Error('Timed out waiting for the event')), ms);
    })]); } finally { clearTimeout(timer); }
  };
  dc.onmessage = ({ data }) => {
    const event = JSON.parse(data);
    onEvent(event);
    if (event.type === 'session.started') resolveStarted(event);
    if (event.type === 'session.closed') { finalEvent = event; resolveClosed(event); }
  };
  pc.ontrack = ({ track, streams }) => {
    audioElement.srcObject = streams[0] || new MediaStream([track]);
    audioElement.play().catch(() => console.log('Click the page to play audio'));
  };
  const cleanup = () => { mic?.getTracks().forEach(track => track.stop()); pc.close(); };
  try {
    mic = await navigator.mediaDevices.getUserMedia({ audio: true });
    mic.getTracks().forEach(track => pc.addTrack(track, mic));
    const gathering = new Promise(resolve => {
      const check = () => {
        if (pc.iceGatheringState === 'complete') {
          pc.removeEventListener('icegatheringstatechange', check); resolve();
        }
      };
      pc.addEventListener('icegatheringstatechange', check); check();
    });
    await pc.setLocalDescription(await pc.createOffer());
    await bounded(gathering, 15000);
    // /api/session is your application backend, not a platform API.
    const response = await fetch('/api/session', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      signal: AbortSignal.timeout(45000), body: JSON.stringify({ sdp: pc.localDescription.sdp }),
    });
    const result = await response.json();
    if (response.status !== 201) throw new Error(JSON.stringify(result));
    sessionId = result.session.id;
    await pc.setRemoteDescription({ type: 'answer', sdp: result.transport.sdp });
    await bounded(started, 30000);
    return { sessionId, async close() {
      try {
        if (finalEvent) return finalEvent.usage;
        if (dc.readyState !== 'open') throw new Error('Control channel disconnected; end the session through backend attach');
        dc.send(JSON.stringify({ type: 'session.close' }));
        return (await bounded(closed, 20000)).usage;
      } finally { cleanup(); }
    }};
  } catch (error) {
    // If a session was created, confirm closing through backend attach; do not recreate automatically.
    if (sessionId) console.error('Session requiring closure confirmation', sessionId);
    if (dc.readyState === 'open') {
      try { dc.send(JSON.stringify({ type: 'session.close' })); await bounded(closed, 15000); } catch {}
    }
    cleanup(); throw error;
  }
}

DataChannel events

Receive transcripts, delegation, cumulative usage and close events. Audio is carried by media tracks; use attach for background configuration and task creation.

Event direction
Category
Event

session.input_audio.mute

Mute or resume input; does not stop output or session billing.

Usage and ending the session

session.usage.updated is a cumulative snapshot; do not sum snapshots. To end the entire session, send session.close, wait for session.closed, and save final usage before releasing the connection. A voice turn ending does not require closing the session.

Voice sessions, background Responses and tool calls may be billed separately. See Model catalog for pricing.

WebRTC usage may also include active_seconds and paused_seconds. The default 15-second initialization precharge offsets later runtime; it is not an additional 15 seconds. Silence or standby does not end the session.

Common issues

SymptomResolution
SDP rejectedUse the complete local Offer from the same connection and preserve line breaks. Add audio tracks and DataChannel and wait for ICE before creation
Created successfully but no soundSet the returned remote SDP and check the microphone, tracks, autoplay policy and ICE connection state
DataChannel control rejectedCheck the allowed-event list; use attach for background configuration and response creation
POST timed out or result unknownCheck whether a session already exists before retrying; do not retry creation automatically. Save any returned session ID so the server can end it
Cannot resume after standbyKeep the microphone track active; check vad_threshold and session.paused/session.resumed