spatiussdkgo

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 6, 2026 License: MIT Imports: 37 Imported by: 0

README

Spatius Golang SDK

codecov Go Report Card Go Reference

Go SDK for Spatius avatar sessions.

Install

go get github.com/spatius-ai/spatius-sdk-go

Quick Start

package main

import (
	"context"
	"log"
	"time"

	spatius "github.com/spatius-ai/spatius-sdk-go"
)

func main() {
	ctx := context.Background()

	session := spatius.NewAvatarSession(
		spatius.WithAPIKey("your-api-key"),
		spatius.WithAppID("your-app-id"),
		spatius.WithAvatarID("your-avatar-id"),
		spatius.WithExpireAt(time.Now().Add(5*time.Minute).UTC()),
		spatius.WithTransportFrames(func(data []byte, last bool) {
			// Handle animation frame bytes.
		}),
	)

	if err := session.Init(ctx); err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	if _, err := session.Start(ctx); err != nil {
		log.Fatal(err)
	}

	audioBytes := []byte{} // Replace with mono PCM audio bytes.
	reqID, err := session.SendAudio(audioBytes, true)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("sent request %s", reqID)
}

Region Resolution

By default the session region is "auto": Init resolves the recommended ingress region via the global bootstrap API and composes the endpoint URLs from the result. Resolution failures never block session initialization — the region falls back to the last successfully resolved region or "us-west".

Pass a concrete region to skip resolution, or explicit endpoint URLs to override region composition entirely:

spatius.NewAvatarSession(
	// ...
	spatius.WithRegion("us-west"), // concrete region: no bootstrap call
)

spatius.NewAvatarSession(
	// ...
	spatius.WithConsoleEndpointURL("https://console.example.com/v1/console"),
	spatius.WithIngressEndpointURL("wss://api.example.com/v2/driveningress"),
)

Session Extra Params

Optional extension parameters can be sent during the WebSocket session handshake. Keys and values must be strings:

spatius.NewAvatarSession(
	// ...
	spatius.WithExtraParams(map[string]string{
		"server_post_process": "false",
	}),
)

Documentation

Detailed usage lives in Spatius docs.

License

MIT

Documentation

Index

Constants

View Source
const (
	// DefaultRegion is the historical fallback region used when automatic
	// region resolution is unavailable.
	DefaultRegion = "us-west"

	// DefaultRegionRequest is the sentinel meaning "let the global bootstrap
	// API schedule the ingress region". This is the default when the user does
	// not pin a region; it is not a usable region by itself and is resolved in
	// AvatarSession.Init.
	DefaultRegionRequest = "auto"

	// DefaultSessionTokenTTL is the default session-token lifetime applied by
	// NewAvatarSession when WithExpireAt is not used.
	DefaultSessionTokenTTL = time.Hour

	// AudioFormatPCMS16LE sends mono 16-bit PCM bytes.
	AudioFormatPCMS16LE AudioFormat = "pcm_s16le"
	// AudioFormatOggOpus sends one continuous Ogg Opus stream per request ID.
	AudioFormatOggOpus AudioFormat = "ogg_opus"
)
View Source
const (
	// DefaultTelemetryEndpoint is the built-in OTLP base endpoint. The SDK derives
	// the /v1/metrics and /v1/traces signal endpoints from it.
	DefaultTelemetryEndpoint = "https://t.spatialwalk.top"
)

Variables

This section is empty.

Functions

func ConfigureTelemetry added in v1.1.0

func ConfigureTelemetry(endpoint string) error

ConfigureTelemetry configures the process-wide OTLP base endpoint.

An empty endpoint disables both metrics and traces. Pass DefaultTelemetryEndpoint to restore the built-in endpoint.

It returns an error when the endpoint is not an absolute HTTP(S) URL, or when a different endpoint is configured after providers have already been initialized. Configure before creating/using a session, or call ShutdownTelemetry first.

func ForceFlushTelemetry added in v1.1.0

func ForceFlushTelemetry()

ForceFlushTelemetry flushes both providers without shutting them down.

func GenerateLogID

func GenerateLogID() (string, error)

GenerateLogID returns a log identifier in the format "YYYYMMDDHHMMSS_<nanoid>". The timestamp is generated in UTC and the nanoid suffix contains 12 characters.

func ShutdownTelemetry added in v1.1.0

func ShutdownTelemetry()

ShutdownTelemetry flushes and shuts down the process-wide providers.

The batch processors export asynchronously. Applications that exit immediately after a session should call ShutdownTelemetry so pending metrics and traces are flushed.

Types

type AgoraEgressConfig

type AgoraEgressConfig struct {
	// ChannelName is the Agora channel name to join
	ChannelName string
	// Token is the Agora token for authentication (optional for testing)
	Token string
	// UID is the publisher UID in the channel (0 for auto-assign)
	UID uint32
	// PublisherID is the publisher identity/name
	PublisherID string
}

AgoraEgressConfig contains configuration for streaming to an Agora channel.

type AudioFormat

type AudioFormat string

AudioFormat identifies the audio encoding negotiated for a session.

type AvatarSDKError

type AvatarSDKError struct {
	Code         AvatarSDKErrorCode
	Message      string
	Phase        string
	ServerCode   string
	ConnectionID string
	ReqID        string
}

AvatarSDKError is an SDK error with a stable error code.

func NewAvatarSDKError

func NewAvatarSDKError(code AvatarSDKErrorCode, message string) *AvatarSDKError

NewAvatarSDKError creates a new AvatarSDKError.

func (*AvatarSDKError) Error

func (e *AvatarSDKError) Error() string

Error implements the error interface.

type AvatarSDKErrorCode

type AvatarSDKErrorCode string

AvatarSDKErrorCode represents stable error codes surfaced by the SDK. These codes are referenced by the v2 websocket API documentation.

const (
	// ErrorCodeSessionTokenExpired indicates the session token has expired.
	ErrorCodeSessionTokenExpired AvatarSDKErrorCode = "sessionTokenExpired"
	// ErrorCodeSessionTokenInvalid indicates the session token is invalid.
	ErrorCodeSessionTokenInvalid AvatarSDKErrorCode = "sessionTokenInvalid"
	// ErrorCodeAppIDUnrecognized indicates the app ID is not recognized.
	ErrorCodeAppIDUnrecognized AvatarSDKErrorCode = "appIDUnrecognized"
	// ErrorCodeInvalidRequest indicates the request payload is invalid.
	ErrorCodeInvalidRequest AvatarSDKErrorCode = "invalidRequest"
	// ErrorCodeInvalidEgressConfig indicates the egress configuration is invalid.
	ErrorCodeInvalidEgressConfig AvatarSDKErrorCode = "invalidEgressConfig"
	// ErrorCodeEgressUnavailable indicates the egress service is unavailable.
	ErrorCodeEgressUnavailable AvatarSDKErrorCode = "egressUnavailable"
	// ErrorCodeProtocolError indicates the websocket protocol exchange was invalid.
	ErrorCodeProtocolError AvatarSDKErrorCode = "protocolError"
	// ErrorCodeConnectionFailed indicates a connection attempt failed or timed out.
	ErrorCodeConnectionFailed AvatarSDKErrorCode = "connectionFailed"
	// ErrorCodeUnknown indicates an unknown error.
	ErrorCodeUnknown AvatarSDKErrorCode = "unknown"
)

type AvatarSession

type AvatarSession struct {
	// contains filtered or unexported fields
}

AvatarSession represents an active avatar session configured via SessionOptions.

func NewAvatarSession

func NewAvatarSession(opts ...SessionOption) *AvatarSession

NewAvatarSession creates a new AvatarSession using the provided SessionOptions.

func (*AvatarSession) Close

func (s *AvatarSession) Close() error

Close closes the WebSocket connection and cleans up resources.

func (*AvatarSession) Config

func (s *AvatarSession) Config() SessionConfig

Config returns a copy of the session configuration.

func (*AvatarSession) Init

func (s *AvatarSession) Init(ctx context.Context) error

Init exchanges configuration credentials for a session token against the console API. It first resolves the ingress region (when set to "auto") via the global bootstrap API and composes the endpoint URLs from the result.

func (*AvatarSession) Interrupt

func (s *AvatarSession) Interrupt() (string, error)

Interrupt sends an interrupt signal to stop the current audio processing. Returns the request ID that was interrupted, or empty string if no request was active.

func (*AvatarSession) SendAudio

func (s *AvatarSession) SendAudio(audio []byte, end bool) (string, error)

SendAudio sends audio data to the server. Audio must match the session's negotiated format unless the internal Ogg Opus encoder is enabled.

func (*AvatarSession) Start

func (s *AvatarSession) Start(ctx context.Context) (string, error)

Start establishes WebSocket connection to the ingress endpoint and performs v2 handshake. Returns the connection ID for tracking this session.

type BootstrapError added in v1.1.0

type BootstrapError struct {
	Message string
}

BootstrapError is returned when the bootstrap request fails or returns an unusable response.

func (*BootstrapError) Error added in v1.1.0

func (e *BootstrapError) Error() string

type EncodedAudioChunk

type EncodedAudioChunk struct {
	Payload         []byte
	CompletedStream []byte
}

EncodedAudioChunk contains a newly encoded payload and the final stream bytes, when requested.

type LiveKitEgressConfig

type LiveKitEgressConfig struct {
	// URL is the LiveKit server URL (e.g., wss://livekit.example.com)
	URL string
	// APIKey is the deprecated LiveKit API key.
	APIKey string
	// APISecret is the deprecated LiveKit API secret.
	APISecret string
	// APIToken is the preferred pre-generated LiveKit access token.
	APIToken string
	// RoomName is the LiveKit room name to join
	RoomName string
	// PublisherID is the publisher identity in the room
	PublisherID string
	// ExtraAttributes are additional key-value attributes for the LiveKit participant.
	ExtraAttributes map[string]string
	// IdleTimeout is the egress connection idle timeout in seconds.
	IdleTimeout int32
}

LiveKitEgressConfig contains configuration for streaming to a LiveKit room.

type OggOpusApplication

type OggOpusApplication string

OggOpusApplication identifies the Opus encoder tuning profile.

const (
	// OggOpusApplicationAudio optimizes encoding for non-voice signals like music.
	OggOpusApplicationAudio OggOpusApplication = "audio"
	// OggOpusApplicationVoIP optimizes encoding for speech.
	OggOpusApplicationVoIP OggOpusApplication = "voip"
	// OggOpusApplicationRestrictedLowdelay optimizes encoding for low-latency use cases.
	OggOpusApplicationRestrictedLowdelay OggOpusApplication = "restricted_lowdelay"
)

type OggOpusEncoderConfig

type OggOpusEncoderConfig struct {
	FrameDurationMS int
	Application     OggOpusApplication
}

OggOpusEncoderConfig configures the optional client-side PCM to Ogg Opus encoder.

type OggOpusStreamEncoder

type OggOpusStreamEncoder struct {
	// contains filtered or unexported fields
}

OggOpusStreamEncoder incrementally encodes mono PCM audio into a continuous Ogg Opus stream.

func NewOggOpusStreamEncoder

func NewOggOpusStreamEncoder(sampleRate int, bitrate int, config *OggOpusEncoderConfig, collectEncodedOutput bool) (*OggOpusStreamEncoder, error)

NewOggOpusStreamEncoder creates an encoder for PCM to Ogg Opus conversion.

func (*OggOpusStreamEncoder) Encode

func (e *OggOpusStreamEncoder) Encode(pcmData []byte, end bool) (EncodedAudioChunk, error)

Encode consumes PCM bytes and returns the next Ogg Opus payload fragment.

type PrewarmOption added in v1.1.0

type PrewarmOption func(*prewarmConfig)

PrewarmOption applies a configuration change to a Prewarm call.

func WithPrewarmAPIKey added in v1.1.0

func WithPrewarmAPIKey(apiKey string) PrewarmOption

WithPrewarmAPIKey sets the console API key. Required only when session token prefetch is enabled via WithPrewarmSessionTokenPrefetch.

func WithPrewarmEndpointURLs added in v1.1.0

func WithPrewarmEndpointURLs(consoleEndpointURL, ingressEndpointURL string) PrewarmOption

WithPrewarmEndpointURLs sets explicit console/ingress endpoint URLs. They override region composition; setting only one composes the other from DefaultRegion, mirroring session initialization.

func WithPrewarmRegion added in v1.1.0

func WithPrewarmRegion(region string) PrewarmOption

WithPrewarmRegion sets the requested region; DefaultRegionRequest ("auto", the default) resolves and caches the recommended region via the bootstrap API.

func WithPrewarmSessionExpireAt added in v1.1.0

func WithPrewarmSessionExpireAt(expireAt time.Time) PrewarmOption

WithPrewarmSessionExpireAt sets the expiration for the prefetched session token. Zero (the default) uses DefaultSessionTokenTTL from now.

func WithPrewarmSessionTokenPrefetch added in v1.1.0

func WithPrewarmSessionTokenPrefetch(enabled bool) PrewarmOption

WithPrewarmSessionTokenPrefetch toggles fetching a session token and caching it so the next AvatarSession.Init with matching credentials skips the console API round trip. It requires WithPrewarmAPIKey.

It assumes the backend allows a token to back more than one session; keep it disabled if tokens are single-use.

func WithPrewarmTLSWarmup added in v1.1.0

func WithPrewarmTLSWarmup(enabled bool) PrewarmOption

WithPrewarmTLSWarmup toggles opening a throwaway TLS connection to each endpoint host (enabled by default).

func WithPrewarmTimeout added in v1.1.0

func WithPrewarmTimeout(timeout time.Duration) PrewarmOption

WithPrewarmTimeout sets the per-operation timeout (default: 5s, the bootstrap resolution timeout).

type PrewarmResult added in v1.1.0

type PrewarmResult struct {
	// Region is the concrete region sessions will use ("" when it could not
	// be resolved).
	Region string
	// ConsoleEndpointURL is the resolved console API URL.
	ConsoleEndpointURL string
	// IngressEndpointURL is the resolved ingress WebSocket URL.
	IngressEndpointURL string
	// TLSWarmed lists the endpoint hosts a warm-up TLS connection was
	// established to.
	TLSWarmed []string
	// SessionTokenPrefetched reports whether a session token was fetched and
	// cached for later Init calls.
	SessionTokenPrefetched bool
}

PrewarmResult is the outcome of a Prewarm call. Fields report what actually succeeded.

func Prewarm added in v1.1.0

func Prewarm(ctx context.Context, appID string, opts ...PrewarmOption) (result PrewarmResult)

Prewarm warms region resolution and connection state ahead of session creation (see the file-level comment). It never returns an error; failures are logged and reported in the result.

type SessionConfig

type SessionConfig struct {
	AvatarID           string
	APIKey             string
	AppID              string
	UseQueryAuth       bool // If true, send app/session credentials as URL query params (web-style auth). If false (default), send them as headers (mobile-style auth).
	ExpireAt           time.Time
	SampleRate         int
	Bitrate            int
	AudioFormat        AudioFormat
	OggOpusEncoder     *OggOpusEncoderConfig
	OnEncodedAudio     func(string, []byte)
	TransportFrames    func([]byte, bool)
	OnError            func(error)
	OnClose            func()
	Region             string
	ConsoleEndpointURL string
	IngressEndpointURL string
	LiveKitEgress      *LiveKitEgressConfig // If set, enables LiveKit egress mode - audio and animation are streamed to a LiveKit room via the egress service
	AgoraEgress        *AgoraEgressConfig   // If set, enables Agora egress mode - audio and animation are streamed to an Agora channel via the egress service
	ExtraParams        map[string]string    // Optional extension parameters sent during the WebSocket session handshake
}

SessionConfig captures the configuration used to build an AvatarSession.

type SessionOption

type SessionOption func(*SessionConfig)

SessionOption applies a configuration change to SessionConfig.

func WithAPIKey

func WithAPIKey(apiKey string) SessionOption

WithAPIKey sets the API key used for authenticating the session.

func WithAgoraEgress

func WithAgoraEgress(config *AgoraEgressConfig) SessionOption

WithAgoraEgress enables Agora egress mode for the session. When set, audio and animation data are streamed to an Agora channel via the egress service instead of being returned through the WebSocket connection.

func WithAppID

func WithAppID(appID string) SessionOption

WithAppID sets the application identifier associated with the session.

func WithAudioFormat

func WithAudioFormat(audioFormat AudioFormat) SessionOption

WithAudioFormat sets the negotiated audio input format.

func WithAvatarID

func WithAvatarID(avatarID string) SessionOption

WithAvatarID sets the avatar identifier used for the session.

func WithBitrate

func WithBitrate(bitrate int) SessionOption

WithBitrate sets the audio bitrate (if applicable to the selected audio format).

func WithConsoleEndpointURL

func WithConsoleEndpointURL(endpointURL string) SessionOption

WithConsoleEndpointURL overrides the default console endpoint URL used by the session.

func WithExpireAt

func WithExpireAt(expireAt time.Time) SessionOption

WithExpireAt sets the expiration time of the session token. When unset, NewAvatarSession defaults it to DefaultSessionTokenTTL from now.

func WithExtraParams added in v1.1.0

func WithExtraParams(extraParams map[string]string) SessionOption

WithExtraParams sets optional extension parameters sent during the WebSocket session handshake. Keys and values must be strings.

func WithIngressEndpointURL

func WithIngressEndpointURL(endpointURL string) SessionOption

WithIngressEndpointURL overrides the default ingress endpoint URL used by the session.

func WithLiveKitEgress

func WithLiveKitEgress(config *LiveKitEgressConfig) SessionOption

WithLiveKitEgress enables LiveKit egress mode for the session. When set, audio and animation data are streamed to a LiveKit room via the egress service instead of being returned through the WebSocket connection.

func WithOggOpusEncoder

func WithOggOpusEncoder(config *OggOpusEncoderConfig) SessionOption

WithOggOpusEncoder enables client-side PCM to Ogg Opus encoding for OGG_OPUS sessions.

func WithOnClose

func WithOnClose(handler func()) SessionOption

WithOnClose registers a handler that is called when the session closes.

func WithOnEncodedAudio

func WithOnEncodedAudio(handler func(string, []byte)) SessionOption

WithOnEncodedAudio registers a handler invoked when internal Ogg Opus encoding completes.

func WithOnError

func WithOnError(handler func(error)) SessionOption

WithOnError registers a handler that receives errors emitted by the session.

func WithRegion

func WithRegion(region string) SessionOption

WithRegion sets the Spatius region used to compose endpoint URLs. Explicit console or ingress endpoint URLs override the region-derived defaults. The default is DefaultRegionRequest ("auto"): the recommended region is resolved via the global bootstrap API during Init. Pass a concrete region (e.g. "us-west") to skip resolution.

func WithSampleRate

func WithSampleRate(sampleRate int) SessionOption

WithSampleRate sets the audio sample rate in Hz.

func WithTransportFrames

func WithTransportFrames(handler func([]byte, bool)) SessionOption

WithTransportFrames registers a handler invoked when transport frames are emitted.

func WithUseQueryAuth

func WithUseQueryAuth(useQueryAuth bool) SessionOption

WithUseQueryAuth chooses whether websocket auth is sent via URL query params (web) or headers (mobile).

Directories

Path Synopsis
examples
connection-pool command
http-service command
proto

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL