Skip to content

Realtime

BrowserRealtimeTransport ports the realtime client WebSocket of ai. It opens a socket for a model that implements IClientRealtimeModel, either with a short-lived client secret (Mode = "client-secret") or through an application relay (Mode = "relay"). A caller without a token must select the relay explicitly.

using var transport = new BrowserRealtimeTransport(
new BrowserRealtimeTransportOptions(model, onServerEvent, onError, onClose)
);
transport.Connect(new BrowserRealtimeConnectOptions
{
Mode = "relay",
Url = "wss://relay.example.com",
OnOpen = () => transport.SendEvent(new RealtimeModelV4ClientEvent("session-update")),
});

By default the transport opens a ClientRealtimeWebSocket, a ClientWebSocket adapter. Set BrowserRealtimeTransportOptions.CreateWebSocket to supply another IRealtimeWebSocket. It stands in for the browser WebSocket constructor. Set BrowserRealtimeTransportOptions.ScheduleTimeout to replace the timer of the one-second drain timeout, for example with a manual clock in tests.

OpenAIRealtimeModel, GatewayRealtimeModel, GoogleRealtimeModel, XaiRealtimeModel, CartesiaRealtimeModel and MistralRealtimeModel implement IClientRealtimeModel, so they work with BrowserRealtimeTransport directly. MistralRealtimeModel also implements ICapableRealtimeModel, and CartesiaRealtimeModel implements IWebSocketConfigRealtimeModel.

A model that mints client secrets implements IClientSecretRealtimeModel (RealtimeModelV4.doCreateClientSecret): DoCreateClientSecretAsync(RealtimeModelV4ClientSecretOptions?, cancellationToken) returns a RealtimeModelV4ClientSecretResult (Token, Url, ExpiresAt). OpenAIRealtimeModel, GatewayRealtimeModel, GatewayRealtimeModelLive, GoogleRealtimeModel, XaiRealtimeModel and CartesiaRealtimeModel implement it, and their provider-specific secret types derive from the result type.

The final URL, from the model or the relay, must be an absolute ws:// or wss:// URL with a host and no fragment. Otherwise Connect throws before it opens a socket.

Continuous Live WebSocket sessions have a 128 KiB outgoing wire-frame limit (EncodeRealtimeFrame.MaxFrameBytes) and a 128 KiB combined buffered-send budget (EncodeRealtimeFrame.MaxBufferedBytes), including the next frame and the JSON or base64 encoding overhead. The transport measures the exact bytes it hands to the socket. Oversized control messages are rejected, not split into several commands. The rejected SendEvent task fails and onError is called. The connection stays open.

These byte caps do not apply to turn-based sessions, which keep their unlimited byte policy.

A model’s SerializeClientEventAsync result is sent as follows:

  • A string JsonValue is sent as text, without JSON encoding.
  • A JsonValue that wraps a byte[], an ArraySegment<byte> or a RealtimeBlob is sent as binary. Only the bytes of the segment count toward the limits.
  • Any other node is sent as its JSON text.

The transport stops accepting writes before it calls OnClosing. It then drains the events it already accepted, for at most one second, and calls OnClose once, with the error that ended the connection, if any. An abnormal close, such as code 1011 or an unclean 1006, is an error.

BrowserRealtimeLiveWebSocket ports the continuous PCM16 runtime of ai. AbstractRealtimeSession uses it for a model whose capabilities declare Conversation = "continuous", over an application relay (Api.Websocket with Api.Protocols) or with a client secret (Api.Token, which needs an explicit client-secret-websocket connection). The browser’s audio APIs have no .NET counterpart, so the host supplies them in RealtimeSessionOptions.AudioEnvironment: a factory for IRealtimeAudioContext (the AudioContext) and, optionally, GetUserMediaAsync for a microphone the session opens itself. A stream you pass in RealtimeConnectOptions.Stream must implement IRealtimeMediaStream, and a continuous session never stops its tracks. A legacy (token-based, turn-based) session takes ownership of a stream you pass and stops its tracks when capture stops, as ai does. A session over a token-based legacy WebSocket also uses GetUserMediaAsync when ResumeAudioCapture has no supplied stream. It owns that stream and stops its tracks when capture stops, the session disconnects, or a late microphone arrives after either.

var session = new MySession(
new RealtimeSessionOptions(model, new RealtimeSessionApi { Websocket = "wss://app.example/live" })
{
AudioEnvironment = new RealtimeAudioEnvironment(
rate => new MyAudioContext(rate),
() => MyMicrophone.OpenAsync()
),
}
);
await session.Connect();
  • The session sends session-start first. The microphone starts once the provider answers session-started.
  • A single-sided InputAudioFormatRate or OutputAudioFormatRate sets both directions. Conflicting rates are left for the provider to validate. The configuration you pass is never mutated.
  • Only audio/pcm at 8000 to 96000 Hz is accepted. Another codec fails before a socket or an audio context is created.
  • MaxPlaybackBufferSeconds (default 2) bounds the playback buffer. Past it, playback pauses and OnError is called until ResumePlayback().
  • Changing the audio format with session-update needs a reconnect. Text, tool output and JSON audio commands are application-owned: use context-append for context.
  • Eight microphone frames with a send still pending are allowed. The next frame fails the connection. A microphone frame that fails to send, for example past the wire budgets above, fails it too. A rejected SendEvent such as an oversized context-append leaves the connection open.

For a non-continuous (legacy) WebSocket session, ResumeAudioCapture() without a stream passed to StartAudioCapture or RealtimeConnectOptions.Stream opens the microphone through AudioEnvironment.GetUserMediaAsync, as resumeAudioCapture does with getUserMedia; without it the call throws UnsupportedFunctionalityException. The session owns that microphone: it stops the tracks when capture stops, when a newer capture request supersedes the pending one, or when the capture cannot start (.NET-only cleanup).

BrowserRealtimeWebRTC ports the WebRTC transport of ai. It exchanges an SDP offer for an answer through your application’s endpoint, opens a data channel for events, publishes the microphone and plays the model’s audio. WebRTC, the microphone and the audio element have no .NET counterpart, so the host supplies them in a RealtimeWebRTCEnvironment: factories for IRealtimePeerConnection, the microphone (IRealtimeMediaStream), IRealtimeAudioElement and a media stream, plus an optional SendAsync that sends the session request.

var environment = new RealtimeWebRTCEnvironment(
() => new MyPeerConnection(),
() => MyMicrophone.OpenAsync(),
() => new MyAudioElement(),
tracks => new MyMediaStream(tracks)
)
{
SendAsync = (request, ct) => appHttpClient.SendAsync(request, ct),
};
using var webrtc = new BrowserRealtimeWebRTC(
new BrowserRealtimeWebRTCOptions(model, onEvent, onError, onClose, onCapturing, onPlaying, environment)
);
await webrtc.ConnectAsync(new BrowserRealtimeWebRTCConnectOptions("https://app.example/realtime", 15_000));
  • BrowserRealtimeWebRTCConnectOptions.TimeoutMs must be greater than zero, and BrowserRealtimeWebRTCOptions.DisconnectTimeoutMs (default 5000) must not be negative. Otherwise the constructor or setter throws ArgumentOutOfRangeException.
  • Api must be an absolute URL unless you set RealtimeWebRTCEnvironment.SendAsync. The default shared HttpClient has no base address, so a relative endpoint throws an ArgumentException before any resource is opened. With SendAsync you resolve the endpoint yourself.
  • The transport serializes its state changes, so timers and peer events from other threads are safe. Dispose reports OnCapturing(false) and OnPlaying(false) only when it retires an existing session, not when ConnectAsync starts the first one.
  • The model must return a RealtimeModelV4WebRTCConfig from GetWebRTCConfig(). IClientRealtimeModel.GetWebRTCConfig is a required member, so a custom IClientRealtimeModel must add it (return null when the model has no WebRTC setup). ConnectAsync then throws InvalidOperationException.

AbstractRealtimeSession (AbstractRealtimeSession in ai) drives BrowserRealtimeWebRTC when RealtimeSessionApi.Session is set. It is the application endpoint that exchanges the SDP offer. The session posts JSON { sdp, sessionConfig } to that endpoint and expects JSON { sdp, sessionId } back. The answer must contain nonempty sdp and sessionId strings (after trimming), and the response body is limited to 1 MiB. On the server, authenticate the application user, validate the offer and the allowed settings, and exchange the SDP with the provider key. The model must return a RealtimeModelV4WebRTCConfig from GetWebRTCConfig(). Otherwise the session throws InvalidOperationException.

The browser’s RTCPeerConnection, getUserMedia, audio element and fetch have no .NET counterpart. The host supplies them in RealtimeSessionOptions.WebRTCEnvironment, the same RealtimeWebRTCEnvironment described above. A WebRTC session without it throws InvalidOperationException.

var session = new MySession(
new RealtimeSessionOptions(model, new RealtimeSessionApi { Session = "https://app.example/api/realtime-live" })
{
WebRTCEnvironment = environment,
RtcDisconnectTimeoutMs = 5_000,
}
);
await session.Connect(new RealtimeConnectOptions { Capture = false });
  • WebRTC negotiates audio through SDP, so omit fixed audio formats and the PCM-only MaxPlaybackBufferSeconds. Audio travels as media, and JSON audio commands are rejected.
  • Connect(new RealtimeConnectOptions { Capture = false }) starts without microphone capture. ResumeAudioCapture() can attach a microphone later.
  • RtcDisconnectTimeoutMs (default 5000) is the grace period for a disconnected peer to recover before the session closes. It must be positive.
  • One live audio track is selected per attachment, preferring an enabled, unmuted track. IsCapturing follows that sender track and never switches tracks automatically. Caller-owned tracks are detached without being stopped or disabled.
  • If detaching a track fails, the peer is closed to stop transmission and the borrowed tracks stay untouched.
  • Autoplay may need a user gesture followed by ResumePlayback().
  • Client delegation stays application-handled, and Live session updates remain unsupported.

Apache-2.0 · Copyright 2023 Vercel, Inc. · unofficial community port, not an official Vercel product