Skip to documentation
svelte/elevenlabs Docs

Docs API reference

API reference

The public controller, options, methods, callbacks, types, and audio helpers, with the defaults that matter.

Entry points

Public exports
ExportKindPurpose
useConversation(options?)ControllerCreates a controller and registers an $effect teardown.
createConversation(options?)FunctionCreates a controller without a lifecycle effect. Call destroy() yourself.
ConversationControllerClassThe reactive controller. Accepts the same options as the factory functions.
ConversationProviderComponentShares a controller through Svelte context.
getConversationContext()FunctionReads the controller from the nearest provider.
setConversationContext(controller)FunctionSupplies a controller to a component subtree.
useConversationClientTool(name, handler)ControllerRegisters a component scoped tool on the provider controller.
AudioManagerClassFramework-agnostic capture, playback, and device engine.
AudioVisualizerComponentCanvas view of the live spectra.
ConversationWidgetComponentComplete conversation surface.

Controller state

These fields are Svelte state or derived values. isTextOnly is a getter. Treat them as read-only from your component and change state through the methods below. The full behavior for each group is covered in Sessions and Audio.

Fields
FieldType
statusConversationStatus
modeConversationMode
canStartboolean
isSpeakingboolean
isListeningboolean
isUserSpeakingboolean
isMutedboolean
isTextOnlyboolean (getter)
volumenumber
inputVolumenumber
outputVolumenumber
transcriptsTranscriptMessage[]
messageCountnumber
messageTranscriptMessage | null
errorstring | null
errorCodeConversationErrorCode | null
latencynumber | null
latencyHistorynumber[]
conversationIdstring | null
inputAudioFormatAudioFormatId | null
outputAudioFormatAudioFormatId | null
queueStatusQueueStatus | null
interruptionsnumber
canSendFeedbackboolean
vadScorenumber
contextUsageContextUsageServerEvent['context_usage_event'] | null
outputGainnumber
inputDeviceIdstring | null
outputDeviceIdstring | null

Methods

Controller methods
MethodReturnsNotes
startConversation(target?, options?)Promise<void>Opens the session. Connection and audio failures populate error. Target can be an agent id, a ws:// or wss:// URL (http and https are normalized), or omitted.
stopConversation()voidEnds the session and preserves the transcript.
endSession()voidAlias for stopConversation().
toggleMute()voidFlips the outgoing mute state.
setMuted(muted)voidSets the outgoing mute state explicitly.
setVolume(volume)voidAccepts a number or { volume: number }. Clamps to 0 through 1.
getInputVolume()numberLatest normalized microphone level.
getOutputVolume()numberLatest normalized playback level.
getInputFrequencyData(target?)Uint8Array512 bins. Reuse a buffer for animation frames.
getOutputFrequencyData(target?)Uint8Array512 bins from agent playback.
getInputByteFrequencyData(target?)Uint8ArrayAlias for getInputFrequencyData.
getOutputByteFrequencyData(target?)Uint8ArrayAlias for getOutputFrequencyData.
getId()string | nullCurrent conversation id.
sendFeedback(like, eventId?)booleanDefaults to the latest agent response. Requires canSendFeedback.
sendUserActivity()booleanThrottled to one frame per second.
sendMCPToolApprovalResult(toolCallId, approved)booleanManual approval path. Sends at most one result per call.
registerClientTool(name, handler)() => voidReturns an unregister function.
changeInputDevice(deviceId?)Promise<boolean>Requires an active voice session.
changeOutputDevice(deviceId?)Promise<boolean>Requires an active voice session and browser output routing.
listAudioDevices()Promise<AudioDeviceInfo[]>Wraps enumerateDevices.
sendContextualUpdate(text, contextId?)booleanNon-interrupting context for the next turn.
sendUserMessage(text)booleanTyped user turn over the same socket.
clearTranscripts()voidLocal only. Does not affect the server conversation.
clearError()voidClears error and errorCode.
destroy()voidReleases its resources. Idempotent.

Options

Every field is optional. The same object is accepted by useConversation, createConversation, the ConversationController constructor, and ConversationProvider.

ConversationOptions
OptionTypeDefault
agentIdstringNone
signedUrlstringNone
signedUrlEndpointstring'/api/signed-url'
originstringOrigin for serverLocation
serverLocation'us' | 'eu-residency' | 'in-residency' | 'global''us'
connectionType'websocket' | 'webrtc''websocket'
textOnlybooleanfalse
dynamicVariablesRecord<string, string | number | boolean>None
userIdstringNone
overridesConversationConfigOverrideNone
clientToolsRecord<string, ClientToolHandler>None
onClientToolCall(call) => string | object | array | PromiseNone
inputDeviceIdstringSystem default
outputDeviceIdstringSystem default
micMutedbooleanfalse
outputVolumenumber1
inputChunkDurationMsnumber100, clamped to 50 through 250
interruptOnUserSpeechbooleantrue
vadThresholdnumber0.075
maxTranscriptsnumber250, minimum 20
resetTranscriptsOnStartbooleantrue
autoCleanupbooleantrue for useConversation
debugbooleanfalse

Callbacks

Session and media callbacks
OptionPayloadWhen
onStatusChangeConversationStatusConnection state changes.
onConnect{ conversationId: string }Metadata negotiation completes.
onDisconnectDisconnectDetailsThe socket closes, including a client stop.
onModeChangeConversationModeThe derived mode label changes.
onTranscriptTranscriptMessageAn entry is created or updated.
onMessageTranscriptMessageAlias for onTranscript.
onErrorConversationErrorA failure is published.
onLatencynumberA time-to-first-audio measurement lands.
onInterruptionNoneLocal or server barge-in is counted.
onCanSendFeedbackChangebooleanFeedback availability changes.
onVadScorenumberThe server reports a voice activity score.
onAudiostringAn agent audio chunk arrives before playback.
onAudioAlignmentAudioAlignmentA chunk includes character timing.
onPing{ event_id, ping_ms? }A keep-alive arrives. The reply is automatic.
onConversationMetadataConversationInitiationMetadataThe initiation metadata arrives.
onConversationIdstringThe conversation id becomes available.
Protocol and tool callbacks
OptionPayloadWhen
onAgentChatResponsePartStreaming partA start, delta, or stop part arrives.
onAgentResponseCorrectionCorrection payloadThe server corrects a response.
onAgentResponseCompletenumberAn agent response finishes.
onAgentResponseMetadataMetadata payloadPer-response metadata arrives.
onContextUsageContext usageThe LLM context window is reported.
onMCPToolCallMCP callAn MCP call changes state.
onMCPConnectionStatusIntegration statusMCP connection state changes.
onMCPToolApprovalRequest(call, { signal }) => booleanA call needs approval.
onAgentToolRequestAgent tool requestThe agent starts a server side tool.
onAgentToolResponseTool responseAn agent tool finishes.
onGuardrailTriggeredGuardrail eventA guardrail fires.
onUnhandledClientToolCallClient callNo named or fallback handler exists.
onIncomingEventServerEventEvery parsed server event.
onOutgoingEventClientEventEvery sent client frame.
onDebugDebugEventStructured diagnostics when debug is on.

Types

Public types
TypeShape
AudioFormat{ encoding: 'pcm' | 'ulaw'; sampleRate: number; channels: 1 }
ConversationStatus'disconnected' | 'connecting' | 'connected'
ConversationMode'disconnected' | 'connecting' | 'ready' | 'listening' | 'speaking'
TranscriptMessageStable id, role, text, isFinal, timestamp, optional event and response ids, attachments.
StartConversationOptions{ signed?: boolean; textOnly?: boolean }
DisconnectDetails{ code: number; reason: string; expected: boolean }
ConversationErrorError with code and optional cause.
ConversationErrorCodeUnion of the 14 stable failure categories.
ClientToolHandler(parameters, call) => unknown | Promise<unknown>
MCPToolApprovalHandler(call, context) => boolean | Promise<boolean>
AudioDeviceInfo{ deviceId, kind, label, groupId }
DebugEvent{ kind, message, data? }

The complete protocol unions, including every server and client event, are exported from svelte-elevenlabs/types. They mirror the ConvAI WebSocket protocol and are safe to import from Node code.

Audio helpers

Exports from svelte-elevenlabs/audio
ExportSignaturePurpose
parseAudioFormat(format: string) => AudioFormatValidate and parse a format id.
resampleLinear(samples, sourceRate, targetRate) => Float32ArrayLinear sample rate conversion.
encodePcm16Base64(samples: Float32Array) => stringEncode mono float samples for user_audio_chunk.
decodePcm16(base64: string) => Float32ArrayDecode base64 PCM16 little-endian.
decodeUlaw(bytes: Uint8Array) => Float32ArrayDecode 8-bit G.711 µ-law.
decodeAudioChunk(base64, format) => Float32ArrayDecode with the negotiated format.
listAudioDevices() => Promise<AudioDeviceInfo[]>Enumerate browser devices.
AudioManagerClassCapture, playback, devices, analysers, and cleanup. Use AudioManager.isSupported() for a capability check.
AudioManagerErrorClassError with a stable audio error code and optional cause.

The full list of failure categories, with causes and fixes, lives in Troubleshooting.

Edit this page on GitHub