Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Voice Agent STT-TTS Pipeline, Turn Metrics, and Client Options

Cloudflare @cloudflare/voice: WebSocket voice pipeline, onTurn, turn outcomes and timings, useVoiceAgent enabled and output device control.

This page summarises Cloudflare documentation on @cloudflare/voice: a real-time voice stack for Cloudflare Agents that streams microphone audio over WebSocket, transcribes speech, runs your logic in onTurn(), synthesises a reply, and plays audio back. The material also covers useVoiceAgent connection gating, speaker routing, and VoiceTurnMetrics for latency and failure diagnosis.

What the voice pipeline does (speech-to-text, model, text-to-speech)

Section titled “What the voice pipeline does (speech-to-text, model, text-to-speech)”

@cloudflare/voice adds a full conversational loop to an Agent backed by a Durable Object: the browser connects over WebSocket while the Worker runs continuous speech-to-text (STT), your onTurn() handler, and text-to-speech (TTS).

The @cloudflare/voice package lets you build real-time voice agents with Cloudflare Agents. It streams microphone audio to an Agent over WebSocket, transcribes speech, runs your model through onTurn(), converts the response to speech, and streams audio back to the caller.

— Cloudflare, Inspect Voice Agent turn latency and outcomes

Cloudflare describes each user utterance as a turn with a fixed stage order:

User speaks → speech-to-text → model → text-to-speech → audio

On the wire, the client sends 16 kHz mono 16-bit PCM as binary WebSocket frames; the server uses model-driven turn detection (the client does not signal end-of-speech for STT). The client can show partial text via transcript_interim messages while the user is still talking. See Voice for the browser ↔ Durable Object diagram and behaviour (interruption handling, streaming TTS, SQLite conversation persistence).

Export / hook Package path Role
withVoice @cloudflare/voice Full agent: STT, LLM via onTurn(), TTS, persistence
withVoiceInput @cloudflare/voice STT-only; no TTS or onTurn()
useVoiceAgent @cloudflare/voice/react React client for withVoice agents
useVoiceInput @cloudflare/voice/react React client for dictation-style STT
VoiceClient @cloudflare/voice/client Framework-agnostic client

Build real-time voice agents with speech-to-text, text-to-speech, and conversation persistence. Audio streams over WebSocket — no SFU or meeting infrastructure required.

— Cloudflare, Voice

Server setup: withVoice, providers, and onTurn(transcript, context)

Section titled “Server setup: withVoice, providers, and onTurn(transcript, context)”

withVoice(Agent) mixes the voice pipeline into your Agent class. You must set a transcriber (continuous per-call STT) and tts provider as class fields so this.env is available after super().

Default Workers AI providers (no extra API keys when using the Workers AI binding) are documented on Voice:

Class Default model Typical use
WorkersAIFluxSTT @cf/deepgram/flux withVoice
WorkersAINova3STT @cf/deepgram/nova-3 withVoiceInput
WorkersAITTS @cf/deepgram/aura-1 Both

onTurn(transcript, context) runs when the user finishes speaking and the transcript is ready. You return a string, AsyncIterable<string>, or ReadableStream (streaming is recommended for LLM replies). context.messages holds completed history before this transcript—append the new user text exactly once when building the model message list. context.signal aborts on interrupt or disconnect.

Optional withVoice() options include historyLimit (default 20), audioFormat (default "mp3"), and maxMessageCount (default 1000). See Voice and the worked Voice agent example for streamText integration and tools.

Pipeline hooks: filter or rewrite each stage

Section titled “Pipeline hooks: filter or rewrite each stage”

Hooks let you intercept STT text, pre-TTS text, or post-TTS audio. Returning null from afterTranscribe skips the current utterance (for example noise or very short transcripts).

Method Receives Can skip utterance?
afterTranscribe(transcript, connection) STT text Yes
beforeSynthesize(text, connection) Text before TTS No (transform only)
afterSynthesize(audio, text, connection) Audio after TTS No

Voice agent shows filtering transcripts shorter than three characters and tweaking pronunciation before synthesis.

Browser client: useVoiceAgent status, enabled, and outputDeviceId

Section titled “Browser client: useVoiceAgent status, enabled, and outputDeviceId”

useVoiceAgent wraps VoiceClient for React: microphone capture, WebSocket connection, playback, mute, interrupts, and optional metrics. status moves through "idle", "listening", "thinking", and "speaking"—enough to drive UI such as the Talk to your knowledge base client (start/end call, interim transcript, finalized transcript turns).

Delay connection until a token is ready (enabled)

Section titled “Delay connection until a token is ready (enabled)”

If your app needs a capability token or other async prerequisite before opening a voice session, pass enabled so the hook does not connect prematurely.

@cloudflare/voice adds an enabled option to useVoiceAgent. React apps can now delay creating and connecting a VoiceClient until prerequisites such as capability tokens are ready.

— Cloudflare, Agents SDK v0.12.4

While enabled: false, the hook stays idle and disconnected; startCall(), sendText(), and sendJSON() are safe no-ops. When enabled becomes true, it connects with the current options (Voice).

Route assistant audio to a chosen speaker (outputDeviceId)

Section titled “Route assistant audio to a chosen speaker (outputDeviceId)”

Voice clients can route assistant audio to a specific output device. Use outputDeviceId with useVoiceAgent, or call client.setOutputDevice() from the framework-agnostic client.

— Cloudflare, Agents SDK improves browser automation

Use a MediaDeviceInfo.deviceId from navigator.mediaDevices.enumerateDevices() where kind === "audiooutput". "default" or undefined keeps the system output. Browsers without HTMLMediaElement.setSinkId() keep playing on the default device and surface a non-fatal outputDeviceError. Device labels may stay blank until microphone permission is granted—refresh the device list after startCall() if you show a speaker picker (Voice).

VoiceClient can call setOutputDevice(selectedSpeakerId) during an active call without reconnecting (Voice).

sendText(text) from useVoiceAgent bypasses STT and goes straight to onTurn(). During an active call the reply is spoken; outside a call the reply appears as text-only transcript messages (Voice).

Turn metrics: outcomes, timings, and turnmetrics events

Section titled “Turn metrics: outcomes, timings, and turnmetrics events”

Older aggregate metrics only covered successful, non-empty speech turns. @cloudflare/voice v0.4.0 adds per-turn inspection of where time goes and how the turn ended.

@cloudflare/voice v0.4.0 now lets you inspect where each Voice Agent turn spends time and how it ends.

— Cloudflare, Inspect Voice Agent turn latency and outcomes

Each speech or text turn emits a typed VoiceTurnMetrics summary with:

  • turnId — correlate events for one turn
  • Terminal outcome — e.g. completed, no_output, output_limit, content_filtered, model_error, tts_error, aborted
  • Stage timings — e.g. speech-to-final-transcript, model-to-first-text, TTS-to-first-audio, total turn duration

These timings can overlap and are not additive. Timings for stages that a turn did not reach are omitted.

— Cloudflare, Inspect Voice Agent turn latency and outcomes

The latest summary is available on VoiceClient, useVoiceAgent(), and useVoiceInput() (input hooks only expose speech/transcription timings they can measure). That lets you tell model silence from output limits, content filtering, or hard failures when the user hears no audio.

Listen for per-turn updates on the framework-agnostic client:

client.addEventListener("turnmetrics", (turn) => {
console.log(turn.outcome, turn.turnTotalMs);
});

useVoiceAgent also exposes rolling pipeline metrics such as llm_ms, tts_ms, first_audio_ms, and total_ms after each turn (Voice).

For development, withVoice(Agent, { diagnostics: { browserConsole: true } }) forwards server lifecycle events to the browser console, combined with local mic, connection, and playback events (model start, first model text, first audio, playback start). Diagnostics are off by default; event names and fields may change (changelog).

VoiceClient exposes typed events for speech-to-text failures, connection errors, and model outcomes. The SDK strips known content fields and does not read arbitrary provider responses, but custom error messages must not contain sensitive data (Inspect Voice Agent turn latency and outcomes).

Compatible versions called out in that release:

npm i @cloudflare/voice@^0.4.0 agents@^0.22.0

STT-only agents (withVoiceInput) and telephony (when you need phone calls)

Section titled “STT-only agents (withVoiceInput) and telephony (when you need phone calls)”

withVoiceInput is for dictation or search-by-voice: continuous STT and onTranscript(text, connection), without TTS, LLM, or onTurn() (Voice). useVoiceInput accumulates utterances into one string for textarea-style UIs.

Telephony adapters (@cloudflare/voice-twilio, @cloudflare/voice-plivo, @cloudflare/voice-telnyx) connect PSTN or WebRTC bridges to the same withVoice agent so web and phone can share state; details differ by provider (server-side Worker adapters vs browser WebRTC for Telnyx). See Voice telephony sections when phone access is a requirement—not when you only need a browser mic UI.

Common mistakes when building voice agents

Section titled “Common mistakes when building voice agents”
  • Summing stage timings — overlap means they are not additive; use outcomes plus individual fields, not a manual sum (turn metrics).
  • Connecting before auth — opening VoiceClient before a token exists; use enabled: Boolean(token) until prerequisites are ready (changelog).
  • Treating all silent replies as model bugs — check outcome for no_output, output_limit, or content_filtered before blaming STT or TTS.
  • Speaker picker before permission — output labels may be empty until mic access; re-enumerate devices after startCall() (Voice).
  • Duplicating the user message — append the current transcript to context.messages only once in onTurn() (Voice).
  • Logging sensitive provider errors — sanitise custom error text shown to users or logs (diagnostics note).
  1. Scaffold or open a project that uses @cloudflare/voice and agents, matching the versions in Inspect Voice Agent turn latency and outcomes if you rely on VoiceTurnMetrics.
  2. Run local dev as in Talk to your knowledge base (npm run dev or your package manager’s dev script), grant microphone access, and confirm status cycles through listening, thinking, and speaking.
  3. Register a turnmetrics listener on VoiceClient or read metrics from useVoiceAgent after a few turns; verify outcome and timings match what you heard (Voice).
  4. Temporarily enable diagnostics.browserConsole on withVoice and confirm correlated server and client events in the browser console during one call (changelog).
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will correct or clarify it.