Skip to main content

Voice

Voice lets a flow speak its replies and lets a client send speech in as text. A voice provider is the object that talks to a speech service: it turns text into audio (text to speech, TTS) and audio into text (transcription). The server holds one provider. A flow can name its own for TTS. The framework cuts a streaming reply into sentences and synthesizes each as it completes, so audio starts before the reply ends and the text is never held back.

The examples use a narration flow and the OpenAI provider from @flow-state-dev/voice-openai.

src/server.ts
import { createFlowState } from "@flow-state-dev/engine";
import { OpenAIVoiceProvider } from "@flow-state-dev/voice-openai";
import { narration } from "./flows/narration/flow";

export const flowState = createFlowState({
flows: [narration()],
voice: { provider: new OpenAIVoiceProvider() },
});
src/flows/narration/flow.ts
import { defineFlow } from "@flow-state-dev/core";

export const narration = defineFlow({
kind: "narration",
voice: { tts: { voice: "alloy", speed: 1.0 } },
actions: {
/* ... */
},
});

Server settings​

SettingTypeMeaning
createFlowState({ voice: { provider } })VoiceProviderThe server's provider, for TTS and transcription.
createFlowApiRouter({ registry, voiceProvider })VoiceProviderThe same provider, on the lower-level router. createFlowState passes its voice.provider here.

Both are optional. With no provider, a flow that asks for TTS skips synthesis, with no error, and its text streams as usual. The transcription endpoint returns 501.

With a provider that has neither speak nor speakStream, a flow that asks for TTS runs text-only and the server writes a warn log line.

Flow settings​

Set on defineFlow({ voice }).

KeyTypeDefaultMeaning
voice.providerVoiceProviderthe server's providerProvider for this flow's TTS. It never applies to the transcription endpoint, which always uses the server's.
voice.ttsobjectabsentTurns TTS on for the flow. A flow without it never speaks.
voice.tts.modelstringnone; the provider's defaultSpeech model id, passed to the provider.
voice.tts.voicestringnone; the provider's defaultProvider-specific voice id.
voice.tts.speednumbernone; the provider's defaultSpeed multiplier, 1.0 is normal. A provider may clamp it.

When a reply is spoken​

A reply is spoken only when:

  1. The flow has voice.tts.
  2. The provider can speak or speakStream.
  3. The request sets metadata.voice.ttsEnabled to true. TTS is off by default.

useVoice sets ttsEnabled for you from its autoPlayTTS option. A client that calls an action itself passes metadata: { voice: { ttsEnabled: true } }. useVoice also sends inputModality: "speech" in the same object.

voiceContext, exported from @flow-state-dev/engine, goes in a generator's context array. When ttsEnabled is set it tells the model to keep sentences short and to avoid markdown, tables, code blocks and bullet lists. When inputModality is "speech" it adds that the user spoke. With no voice metadata it adds nothing.

How a reply is synthesized​

Only assistant messages are voiced.

LookupAnswer
Where a sentence endsAt ., ! or ? followed by whitespace. Text left in the buffer when the message part finishes is sent as the last sentence. It also splits after an abbreviation, so "Dr. Smith" is spoken as two sentences.
Which provider method runsspeakStream() when abilities.speakStream is true, otherwise speak().
What the client receives, streamingA content.added with empty audio, a run of content.audio.delta events, then content.done.
What the client receives, batchcontent.added and content.done, both carrying the full audio.
OrderStrictly by sentence, per message. Every chunk of sentence N goes out before the first chunk of N+1.
ConcurrencyUp to 3 synthesis calls in flight. A streaming call holds its slot until its sentence has gone out.
What a failed sentence doesIt is skipped and text streaming continues. A part that fails mid-stream is closed with content.done.
Timeout15 seconds. See below.

The timeout covers the first chunk of each sentence when streaming, and the whole speak() call in batch. Once a streaming sentence's first chunk arrives, its timer stops, so a long sentence is not cut off. A sentence that times out is abandoned and reported like any failed sentence. When the client disconnects, in-flight synthesis is cancelled. A reverse proxy in front of the server needs an idle timeout longer than 15 seconds.

A failed sentence is reported as a debug event named tts.synthesis.error, not as an error item:

FieldValue
itemIdthe message the sentence belongs to
textthe first 100 characters of the sentence
kindthe VoiceError kind. A thrown error that is not a VoiceError is unknown.
retryablewhether the error was marked retryable
leveldebug for aborted; error for unknown; otherwise info if retryable, else warn
messagethe error message

Debug events are never replayed when a client reconnects. See Items.

Providers​

VoiceProvider​

Exported from @flow-state-dev/core.

MemberTypeMeaning
idstringStable id for telemetry.
providerNamestringShort name, such as "openai" or "composite".
abilities{ speak, speakStream, transcribe, listVoices }Booleans. true means the method exists, false means it is absent. If abilities says true for a method the provider lacks, the framework's call throws a TypeError.
defaultModels?{ speak?, transcribe? }Models used when a call names none. The transcription endpoint reads transcribe.
speak?(options)Promise<{ audio: Uint8Array; mediaType: string }>Batch synthesis.
speakStream?(options)AsyncIterable<{ kind: "audio"; bytes: Uint8Array; mediaType: string; isLast?: boolean }>Streamed synthesis. isLast is set on the final chunk.
transcribe?(options)Promise<{ text: string; language?: string }>Speech to text.
listVoices?()Promise<VoiceInfo[]>The voice catalog.

SpeakOptions are text, voice?, model?, speed?, outputFormat?, signal? and providerOptions?. The framework passes voice, speed and model from voice.tts, plus text and signal, and leaves outputFormat to the provider's default. TranscribeOptions are audio (Uint8Array | Blob), mediaType?, language? (a BCP-47 hint), model?, signal? and providerOptions?. A provider should stop work when signal aborts.

VoiceInfo has id, name, provider, and optional language, accent, gender, age, previewUrl, supportedModels and raw.

canSpeak, canSpeakStream, canTranscribe and canListVoices read abilities.

VoiceError​

A provider throws new VoiceError({ kind, provider, message, retryable?, status?, cause? }), exported from @flow-state-dev/core. It exposes kind, provider, retryable and status. retryable defaults by kind.

kindretryable default
rate_limit, provider_unavailable, networktrue
auth, not_found, invalid_input, format_unsupported, aborted, unknownfalse

createCompositeVoiceProvider​

Builds one provider from several, so TTS and transcription can come from different services.

src/lib/voice.ts
import { createCompositeVoiceProvider } from "@flow-state-dev/core";
import { OpenAIVoiceProvider } from "@flow-state-dev/voice-openai";

export const voice = createCompositeVoiceProvider({
speak: new OpenAIVoiceProvider({ voice: "nova" }),
transcribe: new OpenAIVoiceProvider({ sttModel: "gpt-4o-mini-transcribe" }),
});
SlotMeaning
speak, speakStream, transcribe, listVoicesEach takes a VoiceProvider. All are optional.

providerName is "composite". abilities come from the provider in each slot, so an empty slot, or one whose provider lacks the ability, reports false. With speakStream omitted, the speak provider serves streaming when it advertises speakStream. With no slots every ability is false.

OpenAIVoiceProvider​

From @flow-state-dev/voice-openai. new OpenAIVoiceProvider(options?).

OptionDefaultMeaning
apiKeythe SDK reads OPENAI_API_KEYOpenAI API key.
baseURLOpenAI'sOverride for compatible endpoints or proxies.
organization, projectnoneForwarded to the SDK.
ttsModelgpt-4o-mini-ttsBecomes defaultModels.speak.
sttModelgpt-4o-mini-transcribeBecomes defaultModels.transcribe.
voicealloyDefault voice for speak.
clientnoneA pre-built OpenAI client. When set, apiKey, baseURL, organization and project are ignored.

Abilities: speak, transcribe and listVoices are true; speakStream is false, so TTS with this provider is always batch.

outputFormatMedia type
mp3 (default)audio/mpeg
opusaudio/ogg; codecs=opus
aacaudio/aac
flacaudio/flac
wavaudio/wav
pcmaudio/pcm;rate=24000 (24 kHz, 16-bit little-endian, mono)

Any other format throws format_unsupported. providerOptions.openai.instructions is passed through, and throws invalid_input on tts-1 and tts-1-hd. transcribe with a Uint8Array needs mediaType, or it throws invalid_input. OpenAI returns no language, so the result's language is the one you passed.

listVoices() returns 13 voices: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer, verse, marin and cedar. marin and cedar list supportedModels: ["gpt-4o-mini-tts"].

OpenAI errors map to VoiceError kinds: authentication and permission to auth, rate limit to rate_limit, not found to not_found, a bad request to invalid_input or format_unsupported, a server error to provider_unavailable, a connection failure to network, an abort to aborted, anything else to unknown.

The transcription endpoint​

POST /api/flows/transcribe. It belongs to no flow, always uses the server's provider, requires an authenticated caller, as the session listing does (see Authentication and tenancy), and stores nothing.

FormRequestFields
JSONContent-Type contains application/jsonuserId (required), audio (required, base64), mediaType (default audio/webm), language, model
Rawany other content typeThe body is the audio. Query: userId (required), language, model. mediaType is the Content-Type without parameters, default audio/webm.

Audio over 25 MiB (26,214,400 bytes) is refused. A model is the request's model, else the provider's defaultModels.transcribe. The framework has no default.

200 returns { text, language }. language is absent when the provider returns none.

StatuserrorWhen
400a message naming userIdNo userId.
400a message naming the audioNo audio, or empty audio.
400no_modelNo model in the request (an empty string counts) and no defaultModels.transcribe.
413Audio payload exceeds maximum size of 26214400 bytesAudio over 25 MiB. The raw form checks Content-Length first.
501transcription_not_configuredThe server has no provider.
501provider_does_not_support_transcriptionabilities.transcribe is false.

When the provider throws a VoiceError, the response is { error: <kind>, message } with a status by kind:

kindStatus
invalid_input400
auth401
not_found404
format_unsupported415
aborted499
unknown500
network502
provider_unavailable503
rate_limit429

From a client, client.transcribe({ audio, mediaType?, language? }) takes a Uint8Array or Blob, sends the raw form with the session's userId, and returns { text, language? }. mediaType defaults to audio/webm.

Audio content type​

A spoken reply sentence is an OutputAudioContent, a member of the Content union, imported from @flow-state-dev/core/items.

FieldTypeMeaning
type"output_audio"
audiostringBase64 audio. Empty while streaming.
mediaTypestringFor example audio/mpeg.
transcript?stringThe sentence that was synthesized.
ephemeral?booleanAlways true on audio the framework produces.

Each sentence is its own content part on the assistant message. A streamed part is content.added (empty audio, mediaType audio/mpeg), then content.audio.delta events, then content.done (empty audio, the last chunk's mediaType, the transcript).

content.audio.delta carries { type, itemId, contentIndex, audio, isLast? }, where audio is one base64 chunk.

Audio is not saved with the request's items, so it cannot be read back later; the reply's text is saved as a normal assistant message. On a reconnect, the events that were saved are replayed. A batch sentence comes back whole, with its audio and transcript. A streamed sentence comes back with its transcript and empty audio, because content.audio.delta chunks are never replayed. A client that reconnects mid-sentence hears no more of that sentence. Items lists what is saved and replayed.

useVoice​

useVoice(session, options) from @flow-state-dev/react records the microphone, transcribes it, sends the text to an action and plays the reply.

OptionTypeDefaultMeaning
actionstringrequiredThe action that receives the transcript.
buildInput(text: string) => unknowntext => ({ message: text })Turns the transcript into the action's input.
baseUrlstringnoneBase URL for the transcription call.
apiPathstring"/api/flows"Where the flow API is mounted.
languagestringen-US for browser recognition; none sent to transcriptionRecognition language and transcription hint.
autoPlayTTSbooleantruePlay audio from assistant messages, and set ttsEnabled on each request.
ReturnTypeMeaning
isListeningbooleanThe microphone is recording.
isSpeakingbooleanAudio is playing.
isProcessingbooleanThe server is transcribing.
interimTranscriptstringThe browser's live speech result. Empty without the Web Speech API.
isAvailablebooleangetUserMedia and MediaRecorder exist. false on the first render.
startListening()() => Promise<void>Start recording. Does nothing when unavailable or already listening.
stopListening()() => Promise<void>Stop recording, transcribe, send the action.
stopSpeaking()() => voidStop playback.

stopListening sends the transcript from the server, taken from the whole recording. If transcription throws, it sends the interim transcript instead; with none, nothing is sent and no error surfaces. A blank transcript sends nothing. useVoice plays streamed and batch audio, each part once, and skips replayed parts whose audio is empty.