How Speak becomes a live conversation
Follow Organic LLM’s realtime voice implementation from the first microphone track to playback, tools, and a conversation that survives beyond the call.
Reading contextWebRTC, OpenAI Realtime API, Next.js +1
- WebRTC
- OpenAI Realtime API
- Next.js
- React
- A WebRTC media track carries audio while a separate data channel carries events.
- Follow the Next.js session route for authorization and the React provider for call lifetime.
This reference uses a stated starting profile. Generate a new dissection to adapt it to yours.
1×
Sign in to listen.
One conversation, two paths
The useful place to begin is the boundary between moving sound and running the application. Speak Live captures your microphone in the browser and sends its audio track to OpenAI over a WebRTC peer connection. The model's audio returns on a remote track. Meanwhile, Organic LLM's Next.js routes authorize the session, execute tools, save transcripts, and account for usage.
You can see that division in VoiceTransport. It knows how to connect, send events, expose media streams, and close. It does not know about threads, memories, billing, or the current page. Those belong to useRealtimeVoice and the surrounding server routes. Following this interface first makes the much larger hook easier to read: the hook coordinates a session; the transport moves its media and events.
Loading implementation view…
export interface VoiceTransport {
readonly kind: VoiceTransportKind;
/** Microphone capture. Available after `connect` resolves; the analyser taps it. */
readonly localStream: MediaStream | null;
/** Model audio. Available after `onRemoteStream`; the analyser taps it. */
readonly remoteStream: MediaStream | null;
connect(args: VoiceTransportConnectArgs, events: VoiceTransportEvents): Promise<void>;
/** Client event up to the model. Returns `false` when the channel is not open. */
send(event: Record<string, unknown>): boolean;
close(): void;
}
export type VoiceTransportFactory = () => VoiceTransport;The factory defaults to createWebRtcVoiceTransport, but the interface permits another implementation. The file documents a possible server relay; the implementation inspected here uses a browser-held peer connection. That distinction matters when reasoning about navigation and reloads later.
Keep three objects in mind as you read: a session record on the application server, a peer connection in the browser, and a conversation at the model. They cooperate, but their lifetimes are different. A saved thread can survive a disconnected call; a mounted React component cannot keep a browser connection alive through a document reload.
The server grants a short-lived capability
The browser starts by posting to /api/ai/speak/realtime/session. Before minting credentials, that route checks authentication, resolves the application's user, checks message and Speak budgets, and resolves which thread to continue. It then assembles model instructions and the tools allowed by the session's modality and memory settings.
The important handoff is openai.realtime.clientSecrets.create. The server uses its own API key to create an ephemeral client secret for a configured Realtime session. It returns that secret to the browser. The browser therefore gets permission to connect to this session without receiving the server's long-lived API key.
try {
secretPayload = await openai.realtime.clientSecrets.create({
expires_after: { anchor: "created_at", seconds: 600 },
session: {
type: "realtime",
model,
instructions,
tools,
tool_choice: tools.length > 0 ? "auto" : "none",
max_output_tokens: 800,
// The resumed-thread preamble lives in `instructions`. Retention-ratio truncation drops
// old conversation items when the context fills but never the instructions themselves.
truncation: { type: "retention_ratio", retention_ratio: 0.8 },
audio: {
input: {
turn_detection: { type: "server_vad" },
transcription: { model: "gpt-transcribe" },
},
output: {
voice,
},
},
},
});Read expires_after and turn_detection separately. The first configures the client secret's lifetime: 600 seconds from creation. It is not the application's maximum call duration. That is accounted for in the application's session record and budget machinery.
server_vad delegates voice activity detection to the provider. The app does not implement a local silence detector to decide when you have finished a conversational turn. transcription enables a textual representation of incoming speech, while audio.output.voice chooses the output voice. These are settings on the audio conversation; the transcript is also consumed by the UI and persistence code.
The route registers its own session record after minting and returns both clientSecret and sessionId. This is the bridge between the provider connection and Organic LLM's ownership, continuity, and usage checks.
A microphone track becomes a live call
Back in the browser, the hook creates the transport and passes it the minted secret. connect creates an RTCPeerConnection, subscribes to remote tracks, requests microphone permission, and adds the microphone track. It also creates an oai-events data channel. Audio and JSON events have different jobs even though they share the peer connection.
The microphone permission request is a real boundary: this setup cannot finish without access to an audio input. The transport also watches failed or disconnected peer states and reports them to its caller rather than making UI decisions itself.
async connect({ clientSecret }, events) {
closedByUs = false;
pc = new RTCPeerConnection();
pc.ontrack = (e) => {
remote = e.streams[0] ?? null;
if (remote) events.onRemoteStream(remote);
};
pc.onconnectionstatechange = () => {
if (closedByUs || !pc) return;
if (pc.connectionState === "failed" || pc.connectionState === "disconnected") {
events.onClosed(`Connection ${pc.connectionState}`);
}
};
local = await navigator.mediaDevices.getUserMedia({ audio: true });
pc.addTrack(local.getTracks()[0]!);
dc = pc.createDataChannel("oai-events");
dc.addEventListener("message", (ev) => {
if (typeof ev.data === "string") events.onServerEvent(ev.data);
});
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
const sdpRes = await fetch(REALTIME_CALLS_URL, {
method: "POST",
body: offer.sdp,
headers: {
Authorization: `Bearer ${clientSecret}`,
"Content-Type": "application/sdp",
},
});
createOffer describes the connection the browser wants to establish. That description is SDP, a negotiation format for media and connection capabilities. Posting offer.sdp to /v1/realtime/calls is a setup exchange; it is not an upload of the user's completed recording.
After checking the HTTP response, the transport installs the returned SDP answer with setRemoteDescription. The peer connection can then carry the live media. On the return path, pc.ontrack exposes the model's remote stream. The hook's onRemoteStream callback assigns it to audioEl.srcObject, and the audio element is configured to autoplay.
This is why searching for a loop that downloads successive audio files would lead you astray. In this path, playback is wired to a media stream. Captions and other structured events arrive through a separate channel.
Events turn a stream into an interface
The oai-events channel delivers JSON strings to handleDataEvent. The hook parses them, then delegates interpretation to the pure classifyRealtimeEvent function. That classifier translates provider-specific event names into a smaller application vocabulary: user speech, assistant response, playback, transcript, tool call, and error.
This is a useful seam to study. A provider event is a fact about a remote protocol. A local event is something the application has decided it needs to react to. The classifier keeps the hook from repeating protocol compatibility checks throughout its state updates.
switch (type) {
case "input_audio_buffer.speech_started":
return { kind: "user_speech_started" };
case "input_audio_buffer.speech_stopped":
return { kind: "user_speech_stopped" };
case "response.created":
case "response.output_audio.delta":
case "response.audio.delta":
return { kind: "assistant_started" };
case "response.done":
return { kind: "assistant_finished", usage: usageFromResponseDone(event) };
case "response.output_audio.done":
case "response.audio.done":
return { kind: "assistant_audio_stopped" };
case "output_audio_buffer.started":
return { kind: "assistant_playback_started" };
// `cleared` is the interruption path: the user talked over the model and the buffer was dropped.
case "output_audio_buffer.stopped":
case "output_audio_buffer.cleared":
return { kind: "assistant_playback_stopped" };
case "conversation.item.input_audio_transcription.completed": {Notice the two pairs: response.created / response.done, and output_audio_buffer.started / output_audio_buffer.stopped. Finishing generation does not necessarily mean all buffered audio has reached the speaker. The source explicitly records this distinction, and the idle logic depends on it.
The classifier also accepts both response.output_audio_transcript.* and the older response.audio_transcript.* event names. That compatibility belongs in one place. The hook consumes the resulting transcript events to update captions and buffer completed turns.
When user speech starts, the hook marks the user as speaking and clears its assistant-speaking flag. Playback-cleared events cover the provider's interruption path. The inspected app code reacts to those events; it does not establish every detail of the provider's interruption behavior. That is a boundary to preserve when explaining what this source proves.
A tool call crosses back into the application
A live model can request application work as well as produce speech. When response.function_call_arguments.done arrives, the classifier extracts the call id, name, and serialized arguments. The hook dispatches that call to /api/ai/speak/realtime/tool along with the application's session id.
The server executes the permitted action. Its response can contain a modelResult, which the model needs to continue, and clientEffects, which the interface applies locally. Those are different audiences for the same operation: the model needs a result to reason with, while the reader may need a visual change.
try {
const res = await fetch("/api/ai/speak/realtime/tool", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
sessionId: sid,
callId: call.call_id,
name: call.name,
arguments: call.arguments ?? "{}",
}),
});
const data = (await res.json()) as ToolResponse;
if (data.clientEffects?.length) {
onClientEffects?.(data.clientEffects);
} const transport = transportRef.current;
if (transport) {
transport.send({
type: "conversation.item.create",
item: {
type: "function_call_output",
call_id: call.call_id,
output: JSON.stringify(data.modelResult ?? { ok: data.ok }),
},
});
transport.send({ type: "response.create" });The call_id is the join key. A function_call_output belongs to the original model request, so its id must be carried all the way through the HTTP route and back into the conversation. After submitting the output, the hook sends response.create so the model can continue with the result.
Compare that explicit continuation with silent screen context: buildAmbientContextItem creates a system message describing the current screen, and its delivery path intentionally omits a following response.create. Updating context and asking the model to speak are separate actions. That separation is what allows the voice assistant to gain page context without announcing each navigation.
A tool is counted as activity while it executes. A slow tool should not look like an abandoned conversation just because neither side is making sound.
The call belongs above the page
The location of a connection owner in the React tree is part of this feature's architecture. Organic LLM mounts VoiceSessionProvider in its root layout. The provider owns useRealtimeVoice and a stable audio sink. The Speak page is a view onto that session rather than the owner of the connection.
The source comment gives the reason directly: the App Router preserves the root layout across client-side navigation. Moving the session into a page would tie its lifetime to that page. The provider also keeps its audio element mounted; its comment warns that re-parenting a playing audio element can restart playback.
{/*
The single audio sink for the whole app. It must be rendered here and never inside a
page: re-parenting a playing `<audio>` element restarts it, and unmounting it silences
a live call.
*/}
<audio ref={voice.setAudioElement} autoPlay className="hidden">
<track kind="captions" />
</audio>
{suppressHostBar ? null : (
<VoiceLiveBarHost container={barContainer} pageAnchor={barPageAnchor} />A hard reload is different. It replaces the document, so keeping the provider in a layout cannot preserve that browser's peer connection. The recovery path asks /active about the application session, then mints a successor with resumeSessionId.
On the server, a resumable predecessor must belong to the user, remain active, and have enough time left. The route settles the predecessor before checking whether a new session may start; otherwise the orphaned record could occupy the user's concurrency slot. It inherits the thread and deadline so a reload does not buy more call time.
That is continuity by reconstruction, not a magically immortal connection. Reading the code through that distinction makes both the successful navigation case and the reload case understandable.
Silence is an absence of work
The idle timer is a small module with an unusually consequential definition of “quiet.” It tracks a set of activities: user speech, response generation, actual playback, and individual tools. Beginning any activity cancels the countdown. Ending the last active item starts a fresh countdown.
The default is 20 seconds. The documented reason includes the hot microphone, session limits, and the possibility of room noise creating another turn. The timer should release a call that is truly idle while protecting a long answer or a slow tool.
return {
begin(activity) {
active.add(activity);
disarm();
},
end(activity) {
if (!active.delete(activity)) return;
if (active.size === 0) arm();
},
reset() {
active.clear();
arm();
},
stop() {
active.clear();
disarm();
},The Set matters because activity overlaps. A response may have finished generating while its audio is still playing. A tool may be running while no one speaks. A single isSpeaking boolean would lose those distinctions.
end ignores an activity that never began. Repeated end events therefore do not repeatedly restart the clock. The implementation also deliberately stays open when an activity never receives an end event: its documented choice is to avoid pausing mid-answer. That trades possible lingering sessions for protection against cutting off active work.
When the idle path pauses a session, the hook tears down the transport and settles the server session. The bar can remain in a paused state, with Resume continuing the thread. “Paused” describes the product experience; it does not mean the microphone connection remains running.
The lasting artifact is a conversation
While audio flows over WebRTC, completed transcript turns take an ordinary HTTP path. The hook collects them in turnBufferRef. After an assistant transcript completes, scheduleFlush waits 2.5 seconds before posting the batch. The comment explains why: the user's transcription may finalize asynchronously, after the response has already started, so a short delay helps an exchange land together.
Heartbeats also flush turns, and teardown attempts a final flush before clearing the session id. A failed network request or server error puts a batch back into the buffer for another attempt.
try {
const res = await fetch("/api/ai/speak/realtime/transcript", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId: sid, turns: batch, final }),
// Lets the last flush outlive a closing tab; browsers cap keepalive bodies at 64 KB.
keepalive: final,
});
// 4xx means the session or thread is gone; retrying would not help.
if (!res.ok && res.status >= 500) {
turnBufferRef.current.unshift(...batch);
}
} catch {
// Network blip: keep the turns for the next heartbeat or the final flush.
turnBufferRef.current.unshift(...batch);
}persistSpeakVoiceTurns checks the session and caller ownership, writes the turns as regular UI messages, and schedules title, summary, and optional memory work. It accepts closed sessions because the final flush can race the end request. Authorization comes from the owned session record, not from whether the WebRTC connection is still alive.
Usage takes another related path. response.done contributes provider token usage, the hook accumulates it, and a 30-second heartbeat sends it to the application. If the heartbeat request throws, the usage is restored to the pending total. That is bookkeeping around a live call, not the mechanism that carries its sound.
You can now trace an entire turn: the server mints a capability; the browser negotiates a peer connection; microphone audio reaches the model; media playback and JSON events drive the interface; tool calls return through the application server; transcripts and usage make the session durable and accountable. The implementation becomes easier to comprehend once each of those responsibilities has a place.