Real-Time Voice Agent Interruption and Transport
The model has stopped generating, but the speaker is still playing the rest of its sentence. To debug that interruption, track generation, playback, and conversation state separately.
With OpenAI’s Realtime API (GA since August 28, 2025, Realtime Guide) and Google’s Gemini 3.8 Live (GA since September 15, 2026, Live API Docs), native speech-to-speech sessions have replaced cascaded ASR → LLM → TTS pipelines. Shipping them reliably on web or mobile comes down to transport and audio alignment, ephemeral-token tool loops, and race-safe WebSocket barge-in handling.
Protocol, PCM Format, and Interruption Matrix
Align transport, sample rate, and interruption ownership before implementing audio capture:
| Dimension | Gemini Live API (BidiGenerateContent) |
OpenAI Realtime API (GA) |
|---|---|---|
| Native Transport | Stateful bidirectional WebSocket (WSS) | WebRTC (or SIP) for browsers/mobile; WebSocket for server-to-server bridges |
| PCM Audio Format | Native 16 kHz input (server can also resample declared rates); 24 kHz 16-bit LE mono PCM output (Capabilities) | Configure { type: "audio/pcm", rate: 24000 } under session.audio.input.format and session.audio.output.format (Client Events) |
| Client Auth | Backend calls POST /v1beta/auth_tokens for Ephemeral Tokens |
Backend calls Client Secrets for short-lived client credentials |
| Barge-In & Truncation | Default START_OF_ACTIVITY_INTERRUPTS; client handles serverContent.interrupted and flushes playback |
WebRTC / SIP: server manages output buffer and truncates on barge-in (manual clear uses output_audio_buffer.clear); WebSocket: client flushes playback and sends conversation.item.truncate |
| Updates & GA Migration | Initial setup frame declares model, audio, and tools |
session.update → session.updated; remove legacy OpenAI-Beta: realtime=v1 headers and adopt GA paths |
Watch one subtle trap on OpenAI Realtime WebSocket sessions: input_audio_buffer.speech_started.item_id refers to the upcoming user message and must never be passed to conversation.item.truncate. Always truncate the assistant audio’s item_id, content_index, and actual played audio_end_ms (see Realtime Conversations).
Ephemeral-Token Connection and Closed Tool Loop
Never embed long-lived provider keys in browser or mobile binaries. Keep high-frequency media on the direct client connection while routing privileged tool execution through your backend and returning results to the live session:
Steps 5 through 8 map to distinct wire payloads:
- Gemini Live (Live API Reference): The server sends raw JSON
toolCallevents with function call IDs; the client sendstoolResponsematching those IDs and handlestoolCallCancellationif the user interrupts mid-execution. - OpenAI Realtime (Realtime Conversations): The client creates a
function_call_outputitem with the matchingcall_id, then sendsresponse.createwhen it wants the model to resume generating audio.
Race-Safe WebSocket Barge-In Controller (OpenAI Realtime)
If a newer response starts before an older response’s response.done arrives, unconditionally clearing activeResponseId drops cancellation for the new response. Late audio chunks belonging to an already-interrupted response also need to be discarded.
Scoped specifically to OpenAI Realtime over WebSocket, the controller below tracks active generation and playing audio separately:
export interface WsRealtimeHooks {
sendEvent: (payload: Record<string, unknown>) => void;
stopAndFlushAudio: () => number; // Flushes local audio queue and returns played ms of assistant audio
enqueuePcmChunk: (base64Pcm: string) => void;
}
interface PlayingAudioRef {
responseId: string;
itemId: string;
contentIndex: number;
}
export class WsVoiceTurnController {
private activeResponseId: string | null = null;
private playingAudio: PlayingAudioRef | null = null;
private readonly cancelledResponseIds = new Set<string>();
private readonly hooks: WsRealtimeHooks;
constructor(hooks: WsRealtimeHooks) {
this.hooks = hooks;
}
onServerEvent(event: {
type: string;
response?: { id?: string };
response_id?: string;
item_id?: string;
content_index?: number;
delta?: string;
}): void {
if (event.type === "response.created" && event.response?.id) {
this.activeResponseId = event.response.id;
return;
}
if (event.type === "response.output_audio.delta" && event.delta && event.response_id) {
// Drop late audio chunks from an interrupted response
if (this.cancelledResponseIds.has(event.response_id)) return;
if (event.item_id && typeof event.content_index === "number") {
this.playingAudio = {
responseId: event.response_id,
itemId: event.item_id,
contentIndex: event.content_index,
};
}
this.hooks.enqueuePcmChunk(event.delta);
return;
}
if (event.type === "response.done" && event.response?.id) {
// Clear only when done matches the current active response ID
if (this.activeResponseId === event.response.id) {
this.activeResponseId = null;
}
this.cancelledResponseIds.delete(event.response.id);
return;
}
if (event.type === "input_audio_buffer.speech_started") {
this.interruptActivePlayback();
}
}
interruptActivePlayback(): void {
const playedMs = this.hooks.stopAndFlushAudio();
if (this.activeResponseId) {
const targetId = this.activeResponseId;
this.cancelledResponseIds.add(targetId);
this.hooks.sendEvent({ type: "response.cancel", response_id: targetId });
this.activeResponseId = null;
}
if (this.playingAudio) {
this.hooks.sendEvent({
type: "conversation.item.truncate",
item_id: this.playingAudio.itemId,
content_index: this.playingAudio.contentIndex,
audio_end_ms: Math.max(0, Math.floor(playedMs)),
});
this.playingAudio = null;
}
}
}Local state only avoids redundant cancels—network transit means the server may already have finished a response before response.cancel arrives. Handle the server’s inactive-response error reply (commonly observed as response_cancel_not_active) as benign state reconciliation rather than a fatal disconnect.
Transport, Sample Rate, and Session Lifecycle Boundaries
- Match transport to provider: On lossy mobile networks, use WebRTC for OpenAI Realtime clients (or a self-hosted media bridge for Gemini Live, whose native client transport is WSS).
- Align PCM sample rates end to end: Browsers typically capture at 44.1 kHz or 48 kHz; match 24 kHz for OpenAI GA PCM, or resample to 16 kHz in an
AudioWorklet(or declare the input rate for server resampling) for Gemini Live, with 24 kHz playback output. - Separate three timeouts and monitor usage: Configure ephemeral-token connection TTL, maximum session duration, and idle-silence disconnect independently; monitor live usage against each provider’s audio/text billing rules and enforce tool timeouts so slow external calls never leave the caller in dead air.
References
- Google AI Studio: Gemini Live API Overview
- Google AI Studio: Gemini Live Capabilities
- Google AI Studio: Ephemeral Tokens
- Google AI Studio: Live API Reference
- OpenAI: Realtime API Guide
- OpenAI: Realtime Conversations
- OpenAI: Realtime Client Events
- OpenAI: Realtime Server Events
- OpenAI: Realtime Client Secrets