Voice Providers
Choose and compose realtime or pipeline voice providers with OpenAI, ElevenLabs, Cartesia, and Deepgram.
TechFabric Harness supports two voice modes: realtime, where one model owns audio input, audio output, and tools; and pipeline, where you choose separate STT, LLM, and TTS providers.
Server WebSocket admission errors use VoiceConnectionError with a sanitized code,
optional HTTP status, and retryable classification. Cancellation uses AbortError;
timeouts, rejected handshakes and transport failures remain distinguishable without
retaining provider headers, URLs or raw error messages.
Socket factories and runtimes
Every built-in provider accepts socketFactory. Without it, Node hosts use the optional ws peer
(install it with pnpm add ws); the peer is imported only when a connection opens. On Cloudflare
Workers and Durable Objects, inject the Workers factory:
import { DeepgramSttProvider, OpenAIRealtimeVoiceProvider } from '@fabric-harness/sdk';
import { createWorkersVoiceSocketFactory } from '@fabric-harness/cloudflare/voice';
const socketFactory = createWorkersVoiceSocketFactory();
const realtime = new OpenAIRealtimeVoiceProvider({ apiKey: env.OPENAI_API_KEY, socketFactory });
const stt = new DeepgramSttProvider({ apiKey: env.DEEPGRAM_API_KEY, socketFactory });A custom VoiceSocketFactory receives the URL plus headers, optional protocols, signal,
handshakeTimeoutMs (15 s) and maxPayloadBytes (1 MiB), and it must resolve only with an open
socket or reject with a VoiceConnectionError that retains no headers, URL or provider body, because
callers log and classify that error. Provider
credentials travel in handshake headers and never in the URL. OpenAI and Deepgram use
Authorization, ElevenLabs uses xi-api-key and Cartesia uses X-API-Key.
Transport security
Because every handshake carries an API key, both built-in factories accept only wss:// (or
https://) provider URLs. A plaintext ws:// or http:// URL, including a baseUrl override, is
refused before any connection with a VoiceConnectionError whose code is
VOICE_INSECURE_TRANSPORT. Its message is fixed and doesn't include the URL, and retryable is
false because retrying the same URL can't succeed. For a local test server only, opt in
explicitly:
import { createNodeVoiceSocketFactory, OpenAIRealtimeVoiceProvider } from '@fabric-harness/sdk';
// Local development only. Never enable this in production.
const socketFactory = createNodeVoiceSocketFactory({ allowInsecureTransport: true });
const local = new OpenAIRealtimeVoiceProvider({ apiKey: 'local-test-only', baseUrl: 'ws://127.0.0.1:8080/realtime', socketFactory });On Workers, pass the same allowInsecureTransport option to createWorkersVoiceSocketFactory. A URL
or header value the runtime can't encode (for example an API key with an embedded newline) fails
with VOICE_CONNECT_FAILED; the runtime's own error, which can quote the value, is discarded.
Backpressure and malformed frames
Built-in providers bound outbound audio. sendAudio() (and STT send()) wait while the provider
socket reports more than 512 KiB in bufferedAmount (Node ws). On every runtime, including
Workers sockets that report no buffer size, they also admit at most four times real time for the
session's codec after a 10-second burst. When capacity doesn't free up within 2 seconds, the send
rejects with VoiceBackpressureError (code: 'VOICE_BACKPRESSURE') and the session closes; the Twilio
bridge turns it into a backpressure close. STT send() stays synchronous while the provider keeps
up. Unawaited sends never cause an unhandled rejection; the session emits an error event instead.
A malformed provider frame, such as invalid base64 audio, closes the session with the fixed error
Voice provider protocol error instead of throwing from the socket listener.
Streaming TTS synthesis (ElevenLabs and Cartesia) buffers at most 16 MiB or 4,096 audio chunks
ahead of a consumer that isn't reading. Past that bound the synthesis drops its buffer, closes the
provider socket and throws Voice provider protocol error, prefixed with the provider name.
A consumer that stops early (break out of for await, or iterator.return()) ends the synthesis:
the provider socket is closed, buffered audio is dropped and the abort-signal listener is removed.
iterator.return() settles immediately even while a next() is waiting on a stalled provider. That
pending next() resolves with done: true, and a handshake still in progress is aborted.
A synthesis ends successfully only on the provider's completion marker (ElevenLabs isFinal,
Cartesia done). If the provider socket closes before that marker, for example with code 1011, the
audio already received is still yielded and the next read then throws
connection closed before synthesis completed, prefixed with the provider name; the close code and
reason are never included. Truncated speech is never reported as a completed synthesis.
When the STT provider closes its socket unexpectedly (for example with code 1011), Deepgram and
Cartesia STT sessions end their event stream, and send() rejects with the fixed error
Voice session closed instead of silently dropping audio. PipelineVoiceProvider treats an STT
stream that ends (or fails) without its own close() as fatal. It emits one error event with the
fixed message Speech-to-text connection closed unexpectedly (no close code, reason or provider
detail), then closes the session, so events() ends and sendAudio() rejects. Governed voice and
the Twilio bridge then close the call instead of leaving it connected with no responses.
Deepgram and Cartesia STT open() rejects with an AbortError and closes the socket when its
signal aborts at any point before the session is returned, including just after the handshake
completes.
Choose a voice architecture
The examples below demonstrate low-level transports, not application governance. Use session.voice() for authorized application calls and the Twilio bridge for phone calls. Browser credentials and client-side tool results are not supported by the governed bridge. Provider availability and real phone interoperability require your staging canary.
- Choose OpenAI Realtime when you want a single WebSocket connection with model-managed turn detection and tool calling.
- Choose a Deepgram + ElevenLabs pipeline when independent STT, LLM, and TTS selection matters.
- Choose a Cartesia pipeline when you want STT and TTS from one pipeline provider while retaining your preferred LLM.
- Serve either mode through
WS /sessions/:id/voiceto keep provider credentials on the server.
Mode comparison
| Aspect | Realtime mode | Pipeline mode |
|---|---|---|
| Architecture | One WS, model handles audio in + out + tools | Three streams: STT → LLM → TTS |
| Voice flexibility | Provider's voices only | Any TTS vendor, voice clones, emotion, accents |
| Language support | Provider-bound | Determined by the selected STT and TTS providers |
| Tool calling | Native to the model | Through the underlying LLM (Anthropic/OpenAI/Gemini) |
| Barge-in | Server VAD | STT VAD + caller cancels TTS |
| Useful for | Phone agents, intake bots, simpler audio orchestration | Multilingual, branded voice, vendor flexibility, provider-specific governance |
Provider matrix
| Provider | Role | Fabric integration | Consider when |
|---|---|---|---|
| OpenAI Realtime | Realtime end-to-end | OpenAIRealtimeVoiceProvider | You want one connection for audio, turn detection, responses, and tools. |
| ElevenLabs | TTS | ElevenLabsTtsProvider | Voice selection and TTS controls are central requirements. |
| Cartesia | TTS + STT | CartesiaTtsProvider, CartesiaSttProvider | You want one pipeline vendor for both speech directions. |
| Deepgram | STT | DeepgramSttProvider | You need a dedicated streaming transcription provider with endpointing controls. |
Provider models, languages, and prices change independently of TechFabric Harness. Confirm the current provider offering, then use registerModelPrices to apply your public or negotiated rate card to cost telemetry.
Realtime mode (OpenAI)
import { OpenAIRealtimeVoiceProvider } from '@fabric-harness/sdk';
const provider = new OpenAIRealtimeVoiceProvider({
apiKey: process.env.OPENAI_API_KEY!,
model: 'gpt-realtime',
});
const voice = await provider.connect({
instructions: 'You are a friendly intake agent.',
voice: 'alloy',
audioFormat: 'pcm16', // or 'g711_ulaw' with sampleRate 8000 for Twilio.
tools: [submitFieldTool],
turnDetection: 'server_vad',
});The model owns the audio loop end-to-end. Tool calls relay through the existing tool_call / submitToolResult contract, same as pipeline mode.
Pipeline mode (BYO STT + LLM + TTS)
import {
PipelineVoiceProvider,
DeepgramSttProvider,
ElevenLabsTtsProvider,
AnthropicModelProvider,
} from '@fabric-harness/sdk';
const provider = new PipelineVoiceProvider({
stt: new DeepgramSttProvider({
apiKey: process.env.DEEPGRAM_API_KEY!,
model: 'nova-3',
}),
tts: new ElevenLabsTtsProvider({
apiKey: process.env.ELEVENLABS_API_KEY!,
defaultVoice: '21m00Tcm4TlvDq8ikWAM', // 'Rachel'
model: 'eleven_turbo_v2_5',
}),
llm: new AnthropicModelProvider({ apiKey: process.env.ANTHROPIC_API_KEY! }),
model: 'claude-haiku-4-5-20251001',
});
const voice = await provider.connect({
instructions: 'You are a friendly intake agent. One question at a time.',
audioFormat: 'pcm16',
tools: [submitFieldTool],
});
mic.on('frame', (pcm) => voice.sendAudio(pcm));
for await (const event of voice.events()) {
if (event.type === 'audio_delta') speaker.write(event.audio);
if (event.type === 'tool_call') {
const output = await runTool(event.name, event.input);
await voice.submitToolResult({ id: event.id, output });
}
if (event.type === 'response_done') {
// event.usage contains rolled-up tokens, sttSeconds, ttsCharacters, costUsd.
}
}The contract is identical to realtime mode, VoiceSession events, tool calls, cost telemetry, costBudget, cost_limit events. Swap providers without rewriting your loop.
Single-vendor variant (Cartesia)
import {
PipelineVoiceProvider,
CartesiaSttProvider,
CartesiaTtsProvider,
} from '@fabric-harness/sdk';
const provider = new PipelineVoiceProvider({
stt: new CartesiaSttProvider({ apiKey: process.env.CARTESIA_API_KEY! }),
tts: new CartesiaTtsProvider({ apiKey: process.env.CARTESIA_API_KEY! }),
llm: someLlmProvider,
model: 'claude-haiku-4-5-20251001',
});Barge-in
Pipeline mode wires barge-in through the STT VAD. When the user starts speaking while the agent is mid-utterance, the STT emits speech_started; the pipeline aborts the in-flight LLM call, cancels the TTS stream (ElevenLabs and Cartesia drop audio already buffered, so no frame follows the cancel), and returns to listening. Your UI is responsible for stopping playback when audio_delta events stop arriving.
The pipeline binds each speech_started to the reply in flight when the STT reported it, so
cancelResponse({ interruption }) handled late (after that reply ended and a newer one started) is a
no-op rather than cancelling the newer reply. A new reply emits nothing until the interrupted
reply has finished its cleanup and emitted response_done, bounded at 2 s; past the bound the pipeline emits the interrupted reply's
response_done with the usage known so far, and usage that reply reports later is dropped.
Tool calls and barge-in
A pipeline reply can speak a preamble and request tools in the same model response ("Let me look
that up" plus a lookup call). Its tool calls are emitted as tool_call events, and added to the
conversation history, only after the preamble has been spoken. If the caller barges in during the
preamble, the pipeline records the assistant text (in full; it does not trim to what the caller
heard) without the tool calls: no tool_call is emitted, the tool never runs (governed voice never
sees it), submitToolResult() for its id rejects with Unknown voice tool call, and the next model
request carries no tool call without a matching result, which model providers reject.
Once a tool_call has been emitted, a barge-in no longer cancels it. The session waits for every
result via submitToolResult(); what the caller says meanwhile is queued, and the tool-call
continuation runs before it, so each emitted tool call is always followed by its result in
history. The pipeline commits exactly the tool calls it emitted to history, including when a model
provider reports them in the response rather than on its assistant message.
Input while a reply is in flight
Pipeline mode answers every accepted user turn. Input that arrives while a reply is thinking,
speaking, or waiting for tool results is queued (at most 8 pending turns) and answered in order:
one model call and one response_done per queued turn, each starting only after the previous
turn's response_done. Its user transcript event is emitted when it is accepted. A tool-call
continuation belongs to the reply that requested it and runs before queued turns, and queued
input is never inserted between a tool call and its result.
sendText()with 8 turns already queued rejects with the fixed errorVoice input queue is full; wait for the current replyand emits no transcript. Governed voice closes the call on this rejection, like any other provider failure.- Consecutive final STT transcripts that arrive while a reply is in flight are coalesced into one
pending turn (up to 16,384 characters), because what the caller says during one reply is one
utterance. A final transcript that finds the queue full is dropped and one
errorevent with the same fixed message is emitted; the transcript text is never included. - A barge-in cancels only the reply in flight. Queued turns are kept, and the oldest starts at once
(its events still follow the cancelled reply's
response_done), ahead of anything said after the barge-in. close()discards queued turns without calling the model.
Because each queued sendText() gets its own billed response_done, governed voice's input
journal settles each admitted text input with that turn's reply; input still queued when a call
drops stays outstanding and a same-call reconnect requires reconciliation.
Realtime mode handles this server-side via turnDetection: 'server_vad'. Call
cancelResponse({ playedMs, interruption }) with the milliseconds the caller heard and the
speech_started event you are handling; OpenAI Realtime then cancels and truncates only the reply
that was playing when that event arrived, so its context matches playback. The target is the
response being generated when the event arrived (tracked from response.created, even before its
first audio), otherwise the one whose audio was playing; when neither existed, the cancel sends
no response.cancel at all rather than cancelling whatever is generating later. The
Twilio bridge derives playedMs from Twilio mark echoes, passes
the interruption through, and sends Twilio clear before cancelling.
For phone calls, configure every pipeline stage for μ-law 8 kHz. Setting audioFormat: 'g711_ulaw'
and sampleRate: 8000 on session.voice() passes that codec to both STT and TTS. ElevenLabs emits ulaw_8000 and Cartesia
pcm_mulaw. Nothing resamples. For A-law (g711_alaw), ElevenLabs emits alaw_8000 and Cartesia
TTS emits pcm_alaw. When sampleRate is omitted the pipeline resolves it once, to 24 kHz for
PCM16 or 8 kHz for G.711, and gives both stages that rate, so each provider's own default never
applies.
Every built-in STT and TTS provider emits or expects exactly the format and rate you request, or throws before opening a socket. None substitutes another rate, because audio played at a rate other than the one it was produced at runs at the wrong speed:
| Provider | pcm16 sample rates | g711_ulaw / g711_alaw |
|---|---|---|
| ElevenLabs TTS | 8000, 16000, 22050, 24000 (default), 32000, 44100, 48000 (pcm_<rate>) | 8000 only (ulaw_8000 / alaw_8000) |
| Cartesia TTS | 8000, 16000, 22050, 24000 (default), 44100, 48000 | 8000 only (pcm_mulaw / pcm_alaw) |
| Deepgram STT | any positive integer (default 16000) | 8000 only (mulaw / alaw) |
| Cartesia STT | any positive integer (default 16000) | 8000 only (pcm_mulaw / pcm_alaw) |
ElevenLabs requires a Pro plan or higher for 44.1 kHz PCM. An unsupported combination, such as
ElevenLabs pcm16 at 12000 Hz or g711_ulaw at 16000 Hz, fails with an error naming the provider
and the supported rates. In pipeline mode a TTS rejection surfaces as an error event on the first
reply, so check your format settings in a test call before going live.
Cost telemetry
Both modes feed the same telemetry surface. response_done.usage includes:
{
inputTokens: number; // LLM input
outputTokens: number; // LLM output
audioInputTokens?: number; // realtime mode only
audioOutputTokens?: number;// realtime mode only
sttSeconds?: number; // pipeline mode (Deepgram/Cartesia)
ttsCharacters?: number; // pipeline mode (ElevenLabs/Cartesia)
costUsd?: number; // rolled up via static price table
}Wire costBudget to enforce per-call / per-session / per-tenant ceilings. Voice participates in the same v1.4 cost-budget machinery as text agents.
import { CostBudgetTracker } from '@fabric-harness/sdk';
const budget = new CostBudgetTracker({ perCall: 0.50, perSession: 5 });
await provider.connect({ costBudget: budget });Approving an overrun
With onExceed: 'approve', an over-budget reply emits cost_limit and calls
requestCostLimitApproval. No new model call starts until the approver answers:
const budget = new CostBudgetTracker({ perSession: 5, onExceed: 'approve' });
await provider.connect({
costBudget: budget,
// Resolve true to continue. Resolve false or reject to end the session.
// The approver owns its own timeout.
requestCostLimitApproval: async (violation) => approvals.ask(violation),
});- Pipeline mode. While any budget check is in flight, including a pending approval,
sendText()and final STT transcripts keep queueing, subject to the usual 8-turn bound. A tool-call continuation whose results all arrive during the check also waits. The check starts the moment the reply's model call returns, before itstool_callevents are emitted, so a result submitted as soon as itstool_callarrives cannot start the continuation first. On approval, the continuation runs first and then the queued turns run in order. A later reply that is still over budget asks the approver again. With the defaultonExceed: 'throw', an over-budget reply with tool calls closes the session without a continuation model call. Within budget, the check settles immediately and the continuation runs at once. - Realtime mode. While a budget check is in flight,
sendText()andsubmitToolResult()add their conversation items but holdresponse.create. While an approval is pending, caller audio is also discarded, so server VAD cannot start a response. On approval, the session sends oneresponse.createcovering everything added in the meantime. A response the server had already started when the check began is not cancelled; its cost is checked on its ownresponse_done. Atool_callarrives before its response'sresponse_done, so before that response's cost is known. A result submitted as soon as thetool_callarrives adds itsfunction_call_outputat once, but the continuationresponse.createwaits until that response'sresponse.donehas been processed and its budget check has settled. WithonExceed: 'throw'an over-budget response closes the session without a continuation; with'approve'the continuation is sent only on approval. Within budget it is sent as soon as the check settles, which adds a short delay (the remainder of the response plus one budget check) compared with sending it immediately. Results for several tool calls of one response share a singleresponse.create. - Denial. If the approver resolves
falseor rejects (for example because it timed out), the session emits anerrorevent with the cost-limit message and closes. Queued input is discarded without a model call, and latersendText()calls reject. With the defaultonExceed: 'throw', the session closes the same way, without asking.
Governed voice (session.voice()) has no approval mode. Its costLimit stops the session.
With OpenAI Realtime, a tool result governed voice submits, or a sendText(), does not continue the
conversation until governed voice has recorded and checked the previous reply's cost, so a reply
over costLimit is never continued.
With PipelineVoiceProvider, governed voice holds every model call the same way. From the moment a
reply's model call returns until governed voice has recorded that reply's cost and checked it
against costLimit and the turn limits, no tool-call continuation, queued turn, sendText() or
final speech-to-text transcript starts a model call. Input keeps queueing (same 8-turn bound). Once
the reply is accounted within limits, the continuation runs, then queued turns in order. When a
limit is reached, governed voice closes the session and held work is discarded without a model
call. A reply interrupted before its model call returned holds the next turn until its own
response_done has been accounted, and emits that response_done after at most 2 seconds if its
cancellation never settles. Without governed voice, pipeline behavior is unchanged.
Evaluate a voice stack
Test candidate providers with representative audio before choosing a production stack. Measure:
- time to first transcript and first synthesized audio;
- transcription quality for your languages, accents, vocabulary, and audio channel;
- interruption behavior under real network conditions;
- voice consistency and pronunciation for your domain;
- provider region, retention, residency, and audit controls;
- end-to-end cost using your own traffic distribution and rate card.
Because realtime and pipeline mode share the VoiceSession contract, you can run the same application loop against each candidate and compare session events and usage telemetry.
When to bring your own provider
Implement TtsProvider, SttProvider, or VoiceProvider directly and pass it into PipelineVoiceProvider. Reasons to build your own:
- On-prem TTS (Riva, Coqui) for compliance.
- Whisper-via-vLLM for cheap multilingual STT.
- Translate-on-the-wire layers (e.g. STT in Spanish → MT → English LLM → TTS in Spanish).
The interfaces (TtsProvider, SttProvider) are intentionally narrow, synthesize(text) → AsyncIterable<Uint8Array> and open() → SttSession are the only required methods.
See also
- Voice: the
VoiceSessioncontract and OpenAI Realtime usage. - Cost telemetry: pricing and rate-card overrides.
- Phone calls (Twilio) covers the governed Media Streams bridge and its hosts.