Skip to main content
The Spatius Python SDK creates server-side avatar sessions over WebSocket. It handles session-token creation, WebSocket authentication, audio upload, motion data payload callbacks, and optional egress to LiveKit or Agora.

Repository

The Python SDK is available on GitHub: spatius-ai/spatius-sdk-python and PyPI.
Install the optional Ogg Opus encoder support when you want the SDK to encode raw PCM before sending:
The optional encoder uses opuslib, which requires a working libopus runtime on the host system.

Requirements

  • api_key
  • app_id
  • avatar_id
  • expire_at
  • audio bytes in a supported input format
The SDK defaults to the us-west region. See Regions for the current region list.

Region configuration

Passing a region is enough for normal production use:

Quick Start

Session Configuration

Use new_avatar_session() to configure and create a session:
use_query_auth=False sends WebSocket credentials in headers. Set use_query_auth=True for web-style auth that sends appId and sessionKey in the WebSocket query string.

Session Lifecycle

For audio source and timing guidance, see Audio.

Audio Format

The SDK supports two session-level input formats:
  • AudioFormat.PCM_S16LE - mono 16-bit PCM bytes
  • AudioFormat.OGG_OPUS - one continuous Ogg Opus stream per request ID

PCM Input

  • Sample rate: one of 8000, 16000, 22050, 24000, 32000, 44100, 48000
  • Channels: 1 (mono)
  • Bit depth: 16-bit
  • Format: raw PCM bytes

Ogg Opus Input

  • Sample rate: one of 8000, 12000, 16000, 24000, 48000
  • Channels: 1 (mono)
  • Format: Ogg Opus pages/chunks
  • Request contract: each request ID must carry one continuous Ogg Opus stream across one or more send_audio() calls, and the final chunk must use end=True

Built-In PCM to Ogg Opus Encoder

If you want the session to negotiate AudioFormat.OGG_OPUS but still provide raw PCM bytes to send_audio(), enable the optional internal encoder.
Notes:
  • The internal encoder is optional; if you do not install spatius[opus], keep using PCM or provide pre-encoded Ogg Opus bytes yourself.
  • on_encoded_audio fires when internal encoding completes for a request and receives (req_id, encoded_audio_bytes).
  • If audio_format=AudioFormat.OGG_OPUS and ogg_opus_encoder is unset, send_audio() forwards your pre-encoded Ogg Opus bytes unchanged.

LiveKit Egress Mode

When configured with livekit_egress, audio and motion data are streamed to a LiveKit room instead of being returned through the WebSocket connection. For end-to-end integration details, see the LiveKit Agent server side guide.
api_key and api_secret remain supported for backward compatibility, but they are deprecated. Prefer api_token for new integrations. When LiveKit egress is enabled:
  • the server streams output to the specified LiveKit room
  • the transport_frames callback is not invoked
  • audio and motion data are published under the configured publisher ID

Agora Egress Mode

When configured with agora_egress, audio and motion data are streamed to an Agora channel instead of being returned through the WebSocket connection.

Interrupt

The interrupt() method sends an interrupt signal to stop current audio processing. This is only available when using egress mode.
The interrupt uses the most recent request ID, even after end=True has been sent.

Callbacks

transport_frames

Receives motion data payloads from the server:

on_error

Handles structured SDK errors from the session:
The SDK reports structured AvatarSDKError instances for token creation failures, WebSocket upgrade rejections, handshake failures, runtime ServerError messages, and unexpected connection drops.

on_close

Called when the session closes:

Error Handling

Use SessionTokenError for token creation failures and AvatarSDKError for all other structured SDK errors:
AvatarSDKError and SessionTokenError expose these fields:
  • code - stable SDK error code
  • message - human-readable message
  • phase - failure phase such as session_token, websocket_connect, websocket_handshake, websocket_runtime, or websocket_send
  • http_status - HTTP status for token or WebSocket upgrade failures
  • server_code - server-provided error code, including runtime protobuf ServerError.code
  • server_title / server_detail - parsed server error details when available
  • connection_id / req_id - server correlation identifiers when available
  • raw_body - raw HTTP rejection body for token or WebSocket upgrade failures
  • close_code / close_reason - WebSocket close details for unexpected disconnects

Common AvatarSDKErrorCode Values

  • sessionTokenExpired - session token expired or unauthorized
  • sessionTokenInvalid - invalid or empty session token
  • appIDUnrecognized - App ID is not recognized by the server
  • appIDMismatch - session token belongs to a different app
  • avatarNotFound - avatar does not exist
  • billingRequired - session denied by billing checks
  • creditsExhausted - runtime or connect-time credits exhausted
  • sessionDurationExceeded - billing-enforced session timeout reached
  • unsupportedSampleRate - handshake rejected unsupported audio sample rate
  • invalidEgressConfig - egress config is invalid
  • egressUnavailable - egress service is unavailable or not configured
  • idleTimeout - server closed the session after input inactivity
  • upstreamError - internal upstream service failed
  • protocolError - invalid protobuf or unexpected message sequence
  • connectionFailed - transport-level connection failure
  • connectionClosed - unexpected WebSocket close
  • serverError - server-side failure that did not match a more specific mapping
  • invalidRequest - other client-side request validation errors
  • unknown - fallback when the SDK cannot classify the failure
For server-side error details, see Server Error Codes.

SDK Reference

This page includes usage guidance. The SDK source also keeps developer-facing docstrings on public classes and functions so generated API reference pages can stay close to the code.

new_avatar_session(...)

Creates an AvatarSession from typed keyword parameters. It is the primary public factory.

AvatarSession

Main class for managing avatar sessions.

Methods

  • async init() - initialize the session and obtain a token
  • async start() -> str - start the WebSocket connection and return a connection_id
  • async send_audio(audio: bytes, end: bool = False) -> str - send audio data and return a request ID
  • async interrupt() -> str - interrupt current audio processing in egress mode
  • async close() - close the session and clean up resources
  • config -> SessionConfig - current session configuration

SessionConfig

Configuration dataclass for avatar sessions.

Fields

  • avatar_id: str - avatar identifier
  • api_key: str - API key for authentication
  • app_id: str - application identifier
  • use_query_auth: bool - send WebSocket auth in query params instead of headers
  • expire_at: datetime - session expiration time
  • sample_rate: int - audio sample rate, default 16000
  • bitrate: int - audio bitrate, default 0
  • audio_format: AudioFormat - negotiated input format
  • ogg_opus_encoder: Optional[OggOpusEncoderConfig] - optional PCM to Ogg Opus encoder config
  • on_encoded_audio: Optional[Callable[[str, bytes], None]] - callback for encoded Ogg output
  • transport_frames: Callable[[bytes, bool], None] - frame callback
  • on_error: Callable[[Exception], None] - error callback
  • on_close: Callable[[], None] - close callback
  • region: str - Spatius region. Defaults to us-west; see Regions.
  • console_endpoint_url: str - optional explicit Console API URL
  • ingress_endpoint_url: str - optional explicit ingress WebSocket URL
  • livekit_egress: Optional[LiveKitEgressConfig] - LiveKit egress configuration
  • agora_egress: Optional[AgoraEgressConfig] - Agora egress configuration

LiveKitEgressConfig

Configuration for streaming to a LiveKit room.

Fields

  • url: str - LiveKit server URL, for example wss://livekit.example.com
  • api_key: str - deprecated LiveKit API key
  • api_secret: str - deprecated LiveKit API secret
  • api_token: str - preferred pre-generated LiveKit access token
  • room_name: str - room name to join
  • publisher_id: str - publisher identity in the room
  • extra_attributes: dict[str, str] - extra participant attributes
  • idle_timeout: int - idle timeout in seconds, 0 uses server defaults

AgoraEgressConfig

Configuration for streaming to an Agora channel.

Fields

  • channel_name: str - Agora channel name
  • token: str - Agora token
  • uid: int - publisher UID, 0 for auto-assign
  • publisher_id: str - publisher identity/name

Utility Functions

  • generate_log_id() -> str - generate a unique log ID in the format YYYYMMDDHHMMSS_<nanoid>

Exceptions

  • AvatarSDKError - structured SDK error with stable code and context fields
  • SessionTokenError - subclass of AvatarSDKError raised when session token creation fails

Changelog

spatius-sdk-python releases