Skip to main content

VoiceAgentClient

The main class for real-time voice conversations. Manages the WebSocket connection, audio pipeline, conversation state, and event dispatching.

Constructor

Config Options

Methods

connect(customAudioManager?: AudioManager): Promise<boolean>

Opens a WebSocket connection to the voice agent server.
  • If enableAudio is true (or customAudioManager is provided), initializes the audio pipeline.
  • Sends configuration messages immediately after onopen, in this order: voice, language, tools (only if any are set), visemes, prompt, rates.
  • Starts the microphone if audio management is enabled.
  • Returns true on successful connection.
  • Rejects if the connection fails (e.g., invalid API key, network error).

startManaged(config?: { audioManager?: AudioManager }): Promise<this>

The “Golden Path.” Enables audio management automatically and connects.
  • Sets enableAudio = true.
  • Creates a BrowserAudioManager if in a browser.
  • Throws if called outside a browser without a custom AudioManager.
  • Returns the client instance for chaining.
Must be called inside a user gesture in browsers (e.g., button click).

sendAudio(audioData: Uint8Array): void

Sends raw PCM16 audio data to the server.
  • Format: Int16 PCM, little-endian, 16 kHz, mono
  • Chunk size: ~320 bytes (20 ms)
  • Silently ignored if the WebSocket is not open.

disconnect(): void

Closes the WebSocket connection and releases all resources.
  • Sets isUserDisconnect = true to prevent auto-reconnection.
  • Stops microphone and playback.
  • Cleans up the audio manager.

toggleMute(): boolean

Toggles the microphone mute state.
  • Returns the new mute state (true = muted).
  • No-op if no audio manager is attached.

getAmplitude(): number

Returns the current microphone amplitude.
  • Range: 0 to 1
  • Useful for driving VU meters or visualization.
  • Returns 0 if no audio manager is attached.

updatePrompt(newPrompt: string): void

Updates the system prompt mid-conversation.

updateVoice(voice: VoiceStyle): void

Changes the voice mid-conversation.

updateLanguage(language: Language): void

Changes the language mid-conversation.

updateTools(tools: ToolDefinition[]): void

Replaces the tool definitions mid-conversation.

submitToolResult(callId: string, result: string | object): void

Submits the result of a tool execution back to the LLM.

getTranscript(): Array<{ role: 'user' | 'agent'; text: string; timestamp: number }>

Returns the full conversation history.
  • Each entry includes the speaker role, text, and Unix timestamp.
  • Returns a shallow copy; modifying the array does not affect internal state.

getTranscriptText(): string

Returns the conversation as a formatted text string.

on(event: string, callback: Function): this

Subscribes to an event. Chainable. Supported events: transcription, response, audio, visemes, status, error, tool_call, reconnected, ended ({ code, reason }, the server ended the session), session_limit ({ seconds, reason }, the session’s remaining time when it has a limit).

onAudio(callback: (data: Uint8Array) => void): void

Convenience method equivalent to on('audio', callback).

onVisemes(callback: (visemes: Viseme[]) => void): void

Convenience method equivalent to on('visemes', callback).

Properties

Static Discovery Methods

All REST discovery endpoints are public (no API key). The SDK automatically converts wss:// to https://.

TTSClient

Standalone client for text-to-speech synthesis without the conversational agent.

Constructor

Methods

synthesize(options: SynthesizeOptions): Promise<void>

Opens a temporary WebSocket, sends the synthesis request, and streams back audio.

SynthesizeOptions

The promise resolves when synthesis completes (server sends EOS or closes).

STTClient

Standalone client for one-shot transcription of a complete, pre-recorded audio clip. See Speech-to-Text for the full guide.

Constructor

Methods

transcribe(options: TranscribeOptions): Promise<TranscribeResult>

Returns TranscribeResult: { text, latencyMs, engine, sampleRate, language, durationSeconds, segments? }.

SpeechToTextClient

Standalone client for continuous/live transcription from a microphone, with server-side VAD detecting utterance boundaries. See Speech-to-Text for the full guide.

Constructor

Methods

connect(customAudioManager?: AudioManager): Promise<boolean>

Requests microphone access (or uses customAudioManager, e.g. NodeAudioManager) and starts streaming.

endUtterance(): void

Force-finalizes whatever utterance is currently in progress, instead of waiting for VAD silence.

disconnect(): void

Stops the microphone and closes the connection.

BrowserAudioManager

Manages the Web Audio API pipeline for browser environments.

Constructor

BrowserAudioConfig

requestMicrophone()

Asks for the microphone immediately. Call it synchronously in the click or tap handler that starts a call, before any await, and pass the promise as microphone. iOS Safari reliably shows its permission prompt only for a request made inside a user gesture, and refuses capture outright while the page’s audio session is in 'playback' mode; this function moves that session back to 'auto' first.

Methods

NodeAudioManager

Node.js audio implementation using speaker and node-record-lpcm16.
Dependencies must be installed separately:

Enums

VoiceStyle

Language

Interfaces

Viseme

The SDK receives v, c, t from the server and passes them through as-is.

ToolDefinition

ToolCall

LokutorConfig

SynthesizeOptions

BrowserAudioOptions

Constants

AUDIO_CONFIG

DEFAULT_URLS

Utility Functions

pcm16ToFloat32(int16Data: Int16Array): Float32Array

Converts Int16 PCM to Float32 (-1.0 to 1.0).

float32ToPcm16(float32Data: Float32Array): Int16Array

Converts Float32 to Int16 PCM. Clamps to [-1, 1] before conversion.

resample(input: Float32Array, inputRate: number, outputRate: number): Float32Array

Linear interpolation resampling.

resampleWithAntiAliasing(input: Float32Array, inputRate: number, outputRate: number): Float32Array

Resamples with a low-pass filter to prevent aliasing when downsampling.

normalizeAudio(data: Float32Array, targetPeak?: number): Float32Array

Normalizes audio to a target peak amplitude.

calculateRMS(data: Float32Array | Uint8Array): number

Calculates Root Mean Square amplitude.

StreamResampler

Stateful resampler for streaming audio chunks.

Quick Helpers

simpleConversation(config)

One-liner to create and connect a VoiceAgentClient.

simpleTTS(options)

One-liner for TTS synthesis.

Error Handling

LokutorError

All SDK errors are instances of LokutorError:

isRetryable(error: unknown): boolean

Returns true if the error is a retryable LokutorError:

Error Codes

See the Error Catalog for a complete list of codes, HTTP status mappings, and retry strategies.

Debug Tracing

Enable debug tracing by setting window.LOKUTOR_TRACE = true or localStorage.setItem('lokutorTrace', '1').