Quick Reference
App ID is required on every integration and identifies your Spatius application (it scopes which avatars you can load). Session Token is only required for Direct Mode (
DrivingServiceMode.direct), where it authenticates the Motion Server WebSocket; LiveKit Agents and Agora Convo AI do not need it.AvatarSDK
Main entry point for SDK initialization and global configuration.Static properties
Static methods
initialize(appId, configuration)
Initialize the SDK. Must be called before any other operation.initialize(); set it per view through the AvatarView constructor.
setSessionToken(token)
Set the Session Token used to authenticate the Motion Server WebSocket. Only required in Direct Mode (DrivingServiceMode.direct); AvatarController.start() opens that WebSocket and authenticates with the token.
- Required for
DrivingServiceMode.directbefore callingAvatarController.start(). - Not required for
DrivingServiceMode.rtc(the recommended RTC integrations). That path receives audio and motion data externally and does not open a Motion Server WebSocket from the client;AvatarManager.load()fetches avatar metadata over an App-ID-scoped public endpoint. - The token must be obtained from your backend (see Session token API).
- Maximum 24-hour validity.
- Token must be paired with the App ID used in
initialize().
setSessionToken() can be called before or after initialize(). If called before, the token is applied automatically during initialization.setUserId(userId)
Set a user identifier for logging and telemetry.setRenderQuality(quality)
Update the global rendering quality tier. The default isRenderQuality.ultra; no setter call is required unless you change the tier at runtime. The change takes effect on the next rendered frame across active AvatarView instances.
- Call it after
initialize(). A call made beforeinitialize()is ignored and an error is logged; pass the initial tier asConfiguration.renderQualityinstead. - Calling
setRenderQuality()turns automatic adjustment (setAutoRenderQuality()) off.
setAutoRenderQuality(enabled, options?)
Let the SDK lower the render quality tier when the GPU cannot keep up. Off by default.setAutoRenderQuality() behavior:
- The SDK judges the load only from frames rendered while the Avatar is idle; speaking frames depend on the network and are not used. It lowers the tier one step at a time when the GPU render time exceeds
loadThresholdof the 40 ms frame budget. - With WebGL, which cannot measure GPU time, the SDK lowers the tier when the idle frame rate falls below 25 fps ×
loadThreshold, unless its own per-frame CPU work is the cause. Page scripts that keep the main thread busy also lower the idle frame rate and can trigger a lower tier. - Besides the three tiers, the SDK uses one intermediate step between each pair of tiers. The reported tier is the highest tier not above the current step.
onRenderQualityChangedis called only when that tier changes, withRenderQualityChangeReason.autoDowngradeorRenderQualityChangeReason.autoUpgrade. It is not called forsetRenderQuality(). - A current tier outside
minQuality–maxQualityis moved into that range as soon as automatic adjustment is turned on. - Call it after
initialize(). A call made beforeinitialize(), aloadThresholdoutside 0.6–1.0, or aminQualityabovemaxQualityis ignored and an error is logged. setAutoRenderQuality(false)andsetRenderQuality()both turn automatic adjustment off and keep the current tier. Read the current state fromAvatarSDK.autoRenderQualityEnabled.
setRenderResolutionConfig(enabled, config?)
Keep the render backing-buffer height of everyAvatarView within [minHeight, maxHeight], in physical pixels. The CSS size and aspect ratio of the view are unchanged; the browser scales the canvas to fit. The quality tier’s render scale still applies on top. Off by default.
minHeight: a view shorter than this renders atminHeightand is scaled down. Small views render noticeably sharper, at extra GPU cost.maxHeight: a view taller than this renders atmaxHeightand is scaled up, which saves GPU work on high-DPI displays.- A bound you leave out is not applied.
- A non-positive bound, or a
minHeightabovemaxHeight, makes the call ignored: an error is logged and the current setting is kept. - The change takes effect on the next layout pass across active
AvatarViewinstances. Read the current setting fromAvatarSDK.renderResolutionEnabledandAvatarSDK.renderResolutionConfig.
setRenderResolutionCap(enabled, maxHeight?)
Cap the render backing-buffer height while keeping the same CSS size.maxHeight defaults to 1440. A non-positive maxHeight makes the call ignored: an error is logged and the current setting is kept.
deviceScore()
Run a short CPU/GPU benchmark and return device scores.isDeviceSupported()
Check whether the current device can run AvatarKit. This runs the same benchmark path used bydeviceScore().
cleanup()
Release all SDK resources. Call when the SDK is no longer needed.AvatarManager
Handles avatar asset loading and caching. Access via the singletonAvatarManager.shared.
Static properties
Instance methods
load(id, onProgress?, useCompressedModel?)
Load an avatar by ID. Downloads and caches the avatar’s assets.
Returns:
Promise<Avatar>
cancelLoad(id)
Cancel a pending or running avatar load task.retrieve(id)
Return a cached avatar instance, if available.clear(id)
Clear a specific avatar from cache.clearAll()
Clear all cached avatar resources.AvatarView
3D rendering view. Automatically creates a Canvas element and an associatedAvatarController.
Constructor
setAudioFormat() to change it on a live view.
Render over an Avatar Background
Download the optional 16:9 background from Spatius Studio and store it as an application asset. Set it on the same stage element that you pass toAvatarView; the SDK-created canvas has a transparent background.
Instance properties
AvatarView initializes its renderer asynchronously. The constructor returning is not a readiness signal. For Direct Mode, wait for onFirstRendering before starting the controller; for RTC integrations, wait before creating or connecting an AvatarPlayer.
Transform coordinates
Instance methods
dispose()
Release all view resources. Call when the view is no longer needed (see Lifecycle management for details).exportBitmap()
Capture the current rendered avatar frame as a PNGBlob. Returns null if the canvas is not initialized or not currently rendering.
pauseRendering() / resumeRendering()
Pause or resume GPU/canvas rendering without stopping audio playback.isRenderingEnabled()
Check whether the render loop is currently active.getBoundingRect()
Return the approximate avatar bounds in CSS pixels, ornull if the view is not ready. Recalculate after container size or avatarTransform changes.
AvatarController
Handles runtime communication with Motion Server and playback control.Event callbacks
Instance properties
DrivingServiceMode.direct methods
Available when drivingServiceMode is DrivingServiceMode.direct (the Direct Mode path).
initializeAudioContext()
Initialize the audio context. Must be called inside a user-gesture handler (e.g. aclick listener).
start()
Connect to Motion Server.send(audioData, end)
Send avatar speech audio. Returns theconversationId for the current round.
For audio source and timing guidance, see Audio.
send() behavior:
end: false— continues the current conversation round.end: true— marks the end of audio input for the current round. The avatar plays the remaining animation, then returns to idle (notified viaonConversationState). Sending new audio after this starts a new round and interrupts any ongoing playback.
close()
Close the Motion Server connection.Common methods
Playback, volume, and audio-format controls for a Direct Mode view.setAudioFormat(patch)
Change the audio format of a live view without re-initializing the SDK or reloading the avatar. This is a partial update: fields you leave out keep their current value.channelCount is fixed at 1 and cannot be changed.
setAudioFormat() behavior:
- Whichever field changes, the call interrupts current playback and discards the audio context. In Direct Mode it also disconnects from Motion Server, reported through
onConnectionStateasdisconnected. - You must call
initializeAudioContext()again from a user gesture before the nextsend(). Audio fed after the call is interpreted in the new format. - Switching
inputAudioFormatto'opus'pins the sample rate at 48000. Switching back to'pcm'keeps the current rate unless you pass asampleRatein the same call. - An unsupported
sampleRate, or asampleRatepassed together with Opus input, logs an error and leaves the format unchanged. - Passing values identical to the current format does nothing: no interrupt and no disconnect.
- Read the format now in effect from
controller.audioFormat.
Types and Enums
Configuration
region selects the Spatius deployment region. Supported values are 'us-west', 'ap-northeast', and 'cn-beijing'. When unset, the SDK selects the closest serving region at initialization; passing a value forces that region. If automatic selection cannot be reached, the SDK falls back to a default region and continues initializing. See Regions for endpoint details and override options.
initialize fails fast when appId is missing, rather than returning silently. Get an App ID from app.spatius.ai.DrivingServiceMode
rtc only when driving the avatar through @spatius/avatarkit-rtc. It unlocks no API and does not connect to a room by itself. See the RTC Adapter and the relevant LiveKit Agents Client or Agora Convo AI Client.
RenderQuality
ultra is the default and highest-quality tier. Use high or standard only when you intentionally trade visual quality for lower rendering cost, or let the SDK choose with setAutoRenderQuality().
RenderBackend
Graphics API used to draw the Avatar, set withConfiguration.renderBackend.
initialize(). Rendering fails with ErrorCode.renderNotSupported only when neither WebGPU nor WebGL2 is available.
AutoRenderQualityOptions
Options forAvatarSDK.setAutoRenderQuality(); the option table under setAutoRenderQuality() above describes each field.
RenderQualityChangeReason
Passed toAvatarSDK.onRenderQualityChanged.
RenderResolutionConfig
Height bounds for the render backing buffer, in physical pixels, used byAvatarSDK.setRenderResolutionConfig(). Width follows the view’s aspect ratio. A bound left out is not applied.
FrameStarvationMode
audioIndependent keeps audio playing while motion data catches up. strictSync pauses audio when motion data runs out and resumes when new motion data arrives; use onPlaybackStall to observe those transitions.
AnimationType
LogLevel
ConnectionState
Reported viaonConnectionState. Only emitted when drivingServiceMode is DrivingServiceMode.direct.
ConversationState
Reported viaonConversationState.
State transitions are notified immediately when the transition starts, not when the animation completes. For example,
playing is reported as soon as the transition from idle begins.LoadProgressInfo
AudioFormat
The SDK takes audio as mono PCM16 by default, and can also take Opus. The format is set per view throughAvatarViewOptions.audioFormat and can be changed later with setAudioFormat().
Under
inputAudioFormat: 'opus' the SDK accepts either shape TTS providers produce, and detects which from the bytes:
- Ogg Opus, as file-style APIs return it. Any chunk boundary is fine.
- Bare Opus packets, one per call, as streaming APIs push them over a WebSocket. These cannot be batched: an Opus packet carries no length of its own, so several concatenated into one buffer have no recoverable boundaries.
onError as ErrorCode.invalidAudioInput.
Data size: 1 second at 16 kHz = 16,000 samples × 2 bytes = 32,000 bytes.
Converting MP3 to PCM16
Converting MP3 to PCM16
Error Handling
AvatarError
Error callback
ErrorCode
AvatarError.code is one of the SDK string enum values below.
renderBlankCanvas is delivered through onError when the view reported its first frame, but one second later nothing visible had been drawn (every sampled pixel fully transparent). It is reported at most once per view. An Avatar moved entirely out of the view or scaled to nothing by avatarTransform is reported the same way.
See Client Error Handling for recovery guidance.
Lifecycle Management
Avatar switching
Resource cleanup
dispose() automatically cleans up:
- WebSocket connections
- Audio playback data and animation resources
- Canvas elements and the render system
- Event listeners and callbacks
dispose() reports disconnected through onConnectionState before clearing callbacks.
Fallback mechanism
If the WebSocket connection fails within 15 seconds, the SDK automatically enters audio-only fallback mode — audio continues playing without animation. This keeps playback uninterrupted when Motion Server is unreachable.- Fallback mode is interruptible like normal playback.
onConnectionStatereportsfailedwhen the connection times out.
Browser Compatibility
By default the SDK uses WebGPU when the browser provides it and WebGL2 otherwise. Set
Configuration.renderBackend to prefer one; see RenderBackend.

