Guide
Building a fast voice client
The server decides when the caller has finished, when they have interrupted, and when a call is over. Your client decides how fast that is felt. This page is the client’s half: start quickly, stop playing the instant you are told to, and let go of the call when it ends.
Using the widget? It already does all of this. Read on if you are building your own UI, a mobile app, or a server-side bridge.
Which connection
| You have | Connect to | Protocol |
|---|---|---|
| An agent built in the console | /v1/agents/<publicId>/ws?token=… | Deployment protocol |
| Your own prompt and tools in code | /v1/realtime?model=daisy | OpenAI Realtime (Daisy) |
The advice below applies to both. Where the event names differ, both are given.
1. Start fast
- Do the slow things in parallel. When the user taps Call, ask for the microphone and fetch the connect token at the same time. Opening the socket takes about a second on its own, so nothing else should wait behind it.
- Mint a token per call, at call time. Tokens are single use and short-lived. Do not mint one when the page loads and keep it.
- Do not open sockets ahead of time. An open call holds capacity and is billed while it is open, whether or not anyone talks. Open it when the user starts the call.
- Start streaming once the server says it is ready:
platform.ready(deployment) orsession.created(Daisy). - Daisy: send your settings first. A
session.updatesent straight aftersession.created, before any audio, costs nothing. Changing instructions, tools, voice or language later works too, but pauses the call for about 2 seconds.
2. Send the microphone steadily
- Format: PCM16, little-endian, mono, 24 kHz, base64 in
input_audio_buffer.append. Daisy also accepts 16 kHz PCM, G.711 µ-law and A-law if you declare it insession.update. - Chunks of 20 to 50 ms, on a steady clock. Use an
AudioWorklet, notScriptProcessorNode. Bursts make the turn detector see gaps that are not there. - Keep sending while the call is open, silence included. The server decides when a turn ends from the silence in the audio. You do not need to detect speech yourself, and you should not send
input_audio_buffer.commitorresponse.createafter each sentence. - Muting is fine. If you stop sending mid-sentence, the server ends that turn after about 0.7 s and answers what it heard. Long stretches of silence are not forwarded or billed, so leaving the microphone open costs nothing extra.
- Let the browser cancel echo. Ask for
echoCancellation,noiseSuppressionandautoGainControl, and play the agent through Web Audio in the same page, so the echo canceller hears what it has to remove. On a laptop speaker without it, the agent can hear itself and interrupt itself.
const mic = await navigator.mediaDevices.getUserMedia({
audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, channelCount: 1 },
});
const ctx = new AudioContext({ sampleRate: 24000 });
await ctx.audioWorklet.addModule('/pcm-capture.js'); // posts Int16Array chunks of 480 samples (20 ms)
const capture = new AudioWorkletNode(ctx, 'pcm-capture');
ctx.createMediaStreamSource(mic).connect(capture);
capture.port.onmessage = ({ data }) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'input_audio_buffer.append', audio: toBase64(data.buffer) }));
}
};3. Play the reply as it arrives
- Start on the first delta. Play each
response.output_audio.deltaas it lands. Do not wait forresponse.done: the reply arrives faster than it plays, and waiting adds its whole length to the delay. - Queue in an AudioWorklet with a small cushion, 40 to 80 ms, so network jitter does not cause gaps. Keep the queue in your own code, not in many
AudioBufferSourceNodes scheduled ahead: you have to be able to empty it instantly (next section). - Track what you have actually played for each response, in milliseconds. Daisy needs it when the caller interrupts.
4. Stop instantly on an interruption
When the caller talks over the agent, the server stops generating and tells you about 0.2 s after they start. Everything already in your playback queue is now the agent talking over the caller, so throw it away the moment the signal arrives.
| Connection | Stop playing on |
|---|---|
| Deployment | response.cancelled or platform.barge_in, whichever comes first. Agents on the Daisy card send response.cancelled. |
| Daisy (OpenAI Realtime) | input_audio_buffer.speech_started |
- Empty the queue, do not fade it out. A short ramp of 5 to 10 ms avoids a click; anything longer is the agent still talking.
- Drop late audio for the cancelled reply. A few deltas can still be in flight. Ignore any
response.output_audio.deltawhoseresponse_idyou have already cancelled. - Daisy: tell the server what was heard. Send
conversation.item.truncatewith the reply’sitem_idand the milliseconds you played, as on OpenAI. - Do not cancel on your own speech detection. The server waits for real speech before interrupting, so a cough or a “mhm” does not cut the agent off. A client that stops on its own volume meter undoes that.
const cancelled = new Set();
ws.onmessage = ({ data }) => {
const e = JSON.parse(data);
switch (e.type) {
case 'response.output_audio.delta':
if (!cancelled.has(e.response_id)) player.enqueue(e.response_id, e.delta);
break;
case 'response.cancelled': // deployment protocol
case 'platform.barge_in':
case 'input_audio_buffer.speech_started': { // Daisy
const playing = player.currentResponseId;
if (playing) cancelled.add(playing);
player.flush(); // empty the queue now
break;
}
}
};5. End the call and let go
A call is billed and holds capacity until its socket closes. The server closes calls nobody is using, but closing them yourself is faster and cheaper.
- On hang-up: close the socket with code
1000, stop every microphone track (track.stop()) and close theAudioContext. Closing the socket ends the call on the server at once. - On leaving the page: do the same on
pagehide. Browsers do not reliably close sockets when a tab is discarded. - When the agent ends the call: the server closes the socket after the goodbye has played. Treat a close with code
1000as a normal end and release the microphone. - What the server does if you do not: a call with nobody speaking and the agent silent is closed after its idle limit (60 s by default; close code
4408), and every call ends at its length limit. - One call, one socket. Do not keep a socket open between calls.
6. When the socket closes
| Code | Meaning | Do |
|---|---|---|
1000 | Normal end | Release everything |
1006 | Network dropped | Mint a new token and reconnect once |
1008 | Token or key refused | Do not retry; fix the credential |
1011, 1013 | Server problem or at capacity | Retry once after a few seconds |
4408 | Idle or length limit reached | Do not reconnect on your own; let the user start a new call |
4429 | Too many calls at once (key, workspace or service) | Back off, then retry; the close reason says which limit |
Never reconnect in a loop, and never reuse a token: each one works once.
Checklist
- Microphone and token fetched in parallel; socket opened only when the call starts.
- Daisy settings sent straight after
session.created. - Audio sent in 20 to 50 ms chunks on a steady clock, silence included.
- Echo cancellation on; the agent played through Web Audio in the same page.
- Playback starts on the first delta, from a queue you can empty instantly.
- Queue emptied on
response.cancelled,platform.barge_inorinput_audio_buffer.speech_started; late deltas for that reply dropped. - Socket closed, microphone stopped and audio context closed on hang-up and on
pagehide. - No reconnect loops; a fresh token for every connection.