Repository
The Python SDK is available on GitHub: spatius-ai/spatius-sdk-python and PyPI.opuslib, which requires a working libopus runtime on the host system.
Requirements
api_keyapp_idavatar_idexpire_at- audio bytes in a supported input format
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
Usenew_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
Audio Format
The SDK supports two session-level input formats:AudioFormat.PCM_S16LE- mono 16-bit PCM bytesAudioFormat.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 useend=True
Built-In PCM to Ogg Opus Encoder
If you want the session to negotiateAudioFormat.OGG_OPUS but still provide raw PCM bytes to send_audio(), enable the optional internal encoder.
- 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_audiofires when internal encoding completes for a request and receives(req_id, encoded_audio_bytes).- If
audio_format=AudioFormat.OGG_OPUSandogg_opus_encoderis unset,send_audio()forwards your pre-encoded Ogg Opus bytes unchanged.
LiveKit Egress Mode
When configured withlivekit_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_framescallback is not invoked - audio and motion data are published under the configured publisher ID
Agora Egress Mode
When configured withagora_egress, audio and motion data are streamed to an Agora channel instead of being returned through the WebSocket connection.
Interrupt
Theinterrupt() method sends an interrupt signal to stop current audio processing. This is only available when using egress mode.
end=True has been sent.
Callbacks
transport_frames
Receives motion data payloads from the server:
on_error
Handles structured SDK errors from the session:
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
UseSessionTokenError for token creation failures and AvatarSDKError for all other structured SDK errors:
AvatarSDKError and SessionTokenError expose these fields:
code- stable SDK error codemessage- human-readable messagephase- failure phase such assession_token,websocket_connect,websocket_handshake,websocket_runtime, orwebsocket_sendhttp_status- HTTP status for token or WebSocket upgrade failuresserver_code- server-provided error code, including runtime protobufServerError.codeserver_title/server_detail- parsed server error details when availableconnection_id/req_id- server correlation identifiers when availableraw_body- raw HTTP rejection body for token or WebSocket upgrade failuresclose_code/close_reason- WebSocket close details for unexpected disconnects
Common AvatarSDKErrorCode Values
sessionTokenExpired- session token expired or unauthorizedsessionTokenInvalid- invalid or empty session tokenappIDUnrecognized- App ID is not recognized by the serverappIDMismatch- session token belongs to a different appavatarNotFound- avatar does not existbillingRequired- session denied by billing checkscreditsExhausted- runtime or connect-time credits exhaustedsessionDurationExceeded- billing-enforced session timeout reachedunsupportedSampleRate- handshake rejected unsupported audio sample rateinvalidEgressConfig- egress config is invalidegressUnavailable- egress service is unavailable or not configuredidleTimeout- server closed the session after input inactivityupstreamError- internal upstream service failedprotocolError- invalid protobuf or unexpected message sequenceconnectionFailed- transport-level connection failureconnectionClosed- unexpected WebSocket closeserverError- server-side failure that did not match a more specific mappinginvalidRequest- other client-side request validation errorsunknown- fallback when the SDK cannot classify the failure
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 tokenasync start() -> str- start the WebSocket connection and return aconnection_idasync send_audio(audio: bytes, end: bool = False) -> str- send audio data and return a request IDasync interrupt() -> str- interrupt current audio processing in egress modeasync close()- close the session and clean up resourcesconfig -> SessionConfig- current session configuration
SessionConfig
Configuration dataclass for avatar sessions.
Fields
avatar_id: str- avatar identifierapi_key: str- API key for authenticationapp_id: str- application identifieruse_query_auth: bool- send WebSocket auth in query params instead of headersexpire_at: datetime- session expiration timesample_rate: int- audio sample rate, default16000bitrate: int- audio bitrate, default0audio_format: AudioFormat- negotiated input formatogg_opus_encoder: Optional[OggOpusEncoderConfig]- optional PCM to Ogg Opus encoder configon_encoded_audio: Optional[Callable[[str, bytes], None]]- callback for encoded Ogg outputtransport_frames: Callable[[bytes, bool], None]- frame callbackon_error: Callable[[Exception], None]- error callbackon_close: Callable[[], None]- close callbackregion: str- Spatius region. Defaults tous-west; see Regions.console_endpoint_url: str- optional explicit Console API URLingress_endpoint_url: str- optional explicit ingress WebSocket URLlivekit_egress: Optional[LiveKitEgressConfig]- LiveKit egress configurationagora_egress: Optional[AgoraEgressConfig]- Agora egress configuration
LiveKitEgressConfig
Configuration for streaming to a LiveKit room.
Fields
url: str- LiveKit server URL, for examplewss://livekit.example.comapi_key: str- deprecated LiveKit API keyapi_secret: str- deprecated LiveKit API secretapi_token: str- preferred pre-generated LiveKit access tokenroom_name: str- room name to joinpublisher_id: str- publisher identity in the roomextra_attributes: dict[str, str]- extra participant attributesidle_timeout: int- idle timeout in seconds,0uses server defaults
AgoraEgressConfig
Configuration for streaming to an Agora channel.
Fields
channel_name: str- Agora channel nametoken: str- Agora tokenuid: int- publisher UID,0for auto-assignpublisher_id: str- publisher identity/name
Utility Functions
generate_log_id() -> str- generate a unique log ID in the formatYYYYMMDDHHMMSS_<nanoid>
Exceptions
AvatarSDKError- structured SDK error with stable code and context fieldsSessionTokenError- subclass ofAvatarSDKErrorraised when session token creation fails

