Skip to main content
Version 1.6.0. Install with npm install @lokutor/sdk. Runs in browsers and in Node.js 22 or later (it uses the global WebSocket).

VoiceAgentClient

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

Constructor

Config Options

Constructor callbacks fire once per event, alongside any listeners registered with on() for the same event. They are constructor options only: assigning client.onError = … later does not work (the field is private).

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.
  • Calls auth first, if set, for the credential.
  • Sends configuration messages immediately after onopen, in this order: voice, language, tools (only if any are set), visemes, prompt, rates. With agentId, voice, language and prompt are sent only if you set them.
  • Starts the microphone if audio management is enabled.
  • Returns true on successful connection.
  • Rejects with a LokutorError if the connection fails (invalid credential, network error, a refused handshake) or the microphone cannot start (audio.microphone_unavailable).

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 | 'auto' | ''): void

Changes the language mid-conversation. 'auto' (or '') switches to following the caller.

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 conversation history: final user lines and agent replies. Partial transcripts are not stored.
  • Each entry includes the speaker role, text, and a timestamp (performance.now() milliseconds where available).
  • 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:

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

The discovery endpoints are public (no API key). The methods call https://api.lokutor.com (or the origin of baseUrl).

TTSClient

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

Constructor

apiKey is an API key, or in a browser a wst_ ticket.

Methods

synthesize(options): Promise<void>

Opens a WebSocket to /ws/tts, sends the request, and streams back audio.

SynthesizeOptions

The promise resolves when the server signals the end of the stream (EOS). It rejects with a LokutorError when the server sends an error frame (with the server’s code), with internal.timeout when no audio arrives within 30 s or no further chunk within 15 s, and when the socket closes before the end of the stream (unless audio had arrived and the close was clean).

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. Rejects with audio.microphone_unavailable if the microphone cannot start.

endUtterance(): void

Finalizes the utterance in progress and ends the session: the server sends the final transcript, then closes. Connect again to transcribe more.

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. Pass it to connect() and the client starts the microphone and plays the agent’s audio:
Dependencies must be installed separately:

Enums

VoiceStyle

Use F1–M5: they are the ids GET /voices returns, and each resolves to the native speaker of the session’s language (Voices). In 1.6.0 the JSDoc marks them @deprecated in favour of the explicit EN_* / ESCA_* members, which pin one reference speaker whatever the language; the slot ids remain supported and are what these docs teach. Any voice field also accepts a plain string, such as a clone_… id.

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. The output does not depend on how the input is split into chunks. BrowserAudioManager uses it to bring the microphone down to 16 kHz. When downsampling it low-passes first (since 1.6.1). It uses a 63-tap windowed-sinc filter at 0.45 × the output rate (7.2 kHz for 16 kHz) and then linear interpolation, so sound above the output’s Nyquist frequency does not fold back into the speech band. The filter delays the audio by 31 input samples (0.65 ms at 48 kHz). A flush ends the stream: it drains the filter, returns the remaining audio, and the resampler starts over. Upsampling uses linear interpolation.

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

ErrorCode includes every server code in the Error Catalog (among them billing.insufficient_balance, billing.topup_required, billing.limit_reached, billing.account_disputed and agent.not_found) plus the client-side session.ended, audio.microphone_unavailable and ws.close. retryable is false for authentication, validation, billing, agent.not_found, session.ended and audio.microphone_unavailable. See Error handling for a recipe.

Debug Tracing

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