Skip to main content

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.
For the minimum end-to-end integration walkthrough, open the Web tab in Direct Mode Client.

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.
The audio format is not part of 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.direct before calling AvatarController.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 is RenderQuality.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 before initialize() is ignored and an error is logged; pass the initial tier as Configuration.renderQuality instead.
  • 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 loadThreshold of 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. onRenderQualityChanged is called only when that tier changes, with RenderQualityChangeReason.autoDowngrade or RenderQualityChangeReason.autoUpgrade. It is not called for setRenderQuality().
  • A current tier outside minQuality–maxQuality is moved into that range as soon as automatic adjustment is turned on.
  • Call it after initialize(). A call made before initialize(), a loadThreshold outside 0.6–1.0, or a minQuality above maxQuality is ignored and an error is logged.
  • setAutoRenderQuality(false) and setRenderQuality() both turn automatic adjustment off and keep the current tier. Read the current state from AvatarSDK.autoRenderQualityEnabled.

setRenderResolutionConfig(enabled, config?)

Keep the render backing-buffer height of every AvatarView 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 at minHeight and is scaled down. Small views render noticeably sharper, at extra GPU cost.
  • maxHeight: a view taller than this renders at maxHeight and 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 minHeight above maxHeight, 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 AvatarView instances. Read the current setting from AvatarSDK.renderResolutionEnabled and AvatarSDK.renderResolutionConfig.

setRenderResolutionCap(enabled, maxHeight?)

Deprecated. Use setRenderResolutionConfig(enabled, { maxHeight }) instead. setRenderResolutionCap() and the renderResolutionCapEnabled and renderResolutionMaxHeight properties keep working and will be removed in the next GA release.
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 by deviceScore().

cleanup()

Release all SDK resources. Call when the SDK is no longer needed.

AvatarManager

Handles avatar asset loading and caching. Access via the singleton AvatarManager.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 associated AvatarController.

Constructor

The audio format belongs to the view, so two views on one page can use different sample rates. See AudioFormat for the fields, and setAudioFormat() to change it on a live view.
Container requirement: the container element must have non-zero width and height. The canvas fills the container and auto-resizes via ResizeObserver.

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 to AvatarView; the SDK-created canvas has a transparent background.
For square or portrait display windows, keep this inner stage at 16:9, center it, and clip it with an outer container. See Avatar Background for the shared cropping rules.

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 PNG Blob. 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, or null 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. a click listener).

start()

Connect to Motion Server.

send(audioData, end)

Send avatar speech audio. Returns the conversationId 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 via onConversationState). 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 onConnectionState as disconnected.
  • You must call initializeAudioContext() again from a user gesture before the next send(). Audio fed after the call is interpreted in the new format.
  • Switching inputAudioFormat to 'opus' pins the sample rate at 48000. Switching back to 'pcm' keeps the current rate unless you pass a sampleRate in the same call.
  • An unsupported sampleRate, or a sampleRate passed 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

Use 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 with Configuration.renderBackend.
If the preferred API is unavailable or fails to start, the SDK uses the other one, so the setting never stops an Avatar from rendering on a device that supports either. The setting applies to views created after initialize(). Rendering fails with ErrorCode.renderNotSupported only when neither WebGPU nor WebGL2 is available.

AutoRenderQualityOptions

Options for AvatarSDK.setAutoRenderQuality(); the option table under setAutoRenderQuality() above describes each field.

RenderQualityChangeReason

Passed to AvatarSDK.onRenderQualityChanged.

RenderResolutionConfig

Height bounds for the render backing buffer, in physical pixels, used by AvatarSDK.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 via onConnectionState. Only emitted when drivingServiceMode is DrivingServiceMode.direct.

ConversationState

Reported via onConversationState.
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

Multiply by 100 when rendering as a percentage in your UI.

AudioFormat

The SDK takes audio as mono PCM16 by default, and can also take Opus. The format is set per view through AvatarViewOptions.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.
Opus audio must be mono and must keep one shape for the whole conversation. WebM, MP4, WAV and CAF are not demuxed, even when the Opus inside them is valid. Audio that does not meet these requirements is reported through onError as ErrorCode.invalidAudioInput. Data size: 1 second at 16 kHz = 16,000 samples × 2 bytes = 32,000 bytes.

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
If the Motion Server connection is still open, dispose() reports disconnected through onConnectionState before clearing callbacks.
Always call dispose() when the view is no longer needed. Failing to do so may cause memory leaks.

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.
  • onConnectionState reports failed when 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.

Common Issues


Complete Usage Example