> ## Documentation Index
> Fetch the complete documentation index at: https://docs.spatius.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Go SDK

> Go Server SDK reference for Backend Mode sessions, audio input, callbacks, LiveKit egress, options, and errors.

The Go SDK creates Spatius avatar sessions from backend services. It requests a short-lived session token from the Console API, opens the ingress WebSocket, sends audio, and returns motion data payloads through callbacks.

## Install

```bash theme={null}
go get github.com/spatius-ai/spatius-sdk-go
```

Repository: [spatius-ai/spatius-sdk-go](https://github.com/spatius-ai/spatius-sdk-go)

## Quick start

```go theme={null}
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 motion data payloads.
		}),
		spatius.WithOnError(func(err error) {
			// Handle async session errors.
		}),
		spatius.WithOnClose(func() {
			// Handle connection close.
		}),
	)

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

	connectionID, err := session.Start(ctx)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("connection id: %s", connectionID)

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

## Region configuration

The SDK defaults to `us-west` when no region is provided, or when `WithRegion` receives an empty or whitespace-only value. See [Regions](/api-reference/regions) for the current region list. To set a region:

```go theme={null}
session := spatius.NewAvatarSession(
	spatius.WithRegion("us-west"),
)
```

## Session lifecycle

1. Create a session with `NewAvatarSession`.
2. Call `Init(ctx)` to exchange the API key and expiry time for a session token.
3. Call `Start(ctx)` to open the ingress WebSocket and configure the avatar session.
4. Call `SendAudio(audio, end)` for each audio chunk.
5. Call `Interrupt()` when playback should stop.
6. Call `Close()` when the session is done.

`SendAudio` returns the request ID associated with the audio. The callback passed to `WithTransportFrames` receives motion data payloads and a `last` flag.

For audio source and timing guidance, see [Audio](/concepts/audio).

## Audio format

PCM 16-bit little-endian is the default input format:

```go theme={null}
session := spatius.NewAvatarSession(
	spatius.WithSampleRate(24000),
	spatius.WithAudioFormat(spatius.AudioFormatPCMS16LE),
)
```

The SDK also supports Ogg Opus sessions:

```go theme={null}
session := spatius.NewAvatarSession(
	spatius.WithAudioFormat(spatius.AudioFormatOggOpus),
	spatius.WithSampleRate(24000),
	spatius.WithBitrate(32000),
	spatius.WithOggOpusEncoder(nil),
)
```

Passing `nil` to `WithOggOpusEncoder` enables the default encoder config.

## Authentication mode

By default, WebSocket authentication is sent in headers:

```go theme={null}
session := spatius.NewAvatarSession(
	spatius.WithUseQueryAuth(false),
)
```

For web-style query authentication, enable:

```go theme={null}
session := spatius.NewAvatarSession(
	spatius.WithUseQueryAuth(true),
)
```

## LiveKit egress

<Note>
  Server SDK egress is a low-level capability, not an additional integration path. Use [LiveKit Agents Integration](/livekit-agents/overview) for the supported LiveKit Agents workflow.
</Note>

Use LiveKit egress when Spatius should publish avatar output directly into a LiveKit room:

```go theme={null}
session := spatius.NewAvatarSession(
	spatius.WithLiveKitEgress(&spatius.LiveKitEgressConfig{
		URL:         "wss://your-livekit-server.com",
		APIToken:    "livekit-access-token",
		RoomName:    "room-name",
		PublisherID: "avatar-publisher",
		ExtraAttributes: map[string]string{
			"role": "avatar",
		},
		IdleTimeout: 60,
	}),
)
```

Prefer `APIToken` for new integrations. `APIKey` and `APISecret` remain available for older setups.

## Options

Core options:

* `WithAPIKey(apiKey string)` - Console API key.
* `WithAppID(appID string)` - application ID.
* `WithAvatarID(avatarID string)` - avatar ID.
* `WithExpireAt(expireAt time.Time)` - session token expiry.
* `WithRegion(region string)` - region used to select the Spatius region. Empty or whitespace-only values fall back to `us-west`.
* `WithConsoleEndpointURL(endpointURL string)` - explicit Console API URL.
* `WithIngressEndpointURL(endpointURL string)` - explicit ingress WebSocket URL.

Audio options:

* `WithSampleRate(sampleRate int)` - input sample rate in Hz.
* `WithBitrate(bitrate int)` - target bitrate for encoded sessions.
* `WithAudioFormat(audioFormat AudioFormat)` - `AudioFormatPCMS16LE` or `AudioFormatOggOpus`.
* `WithOggOpusEncoder(config *OggOpusEncoderConfig)` - enable client-side PCM to Ogg Opus encoding.

Callbacks:

* `WithTransportFrames(func([]byte, bool))` - receives motion data payloads.
* `WithOnEncodedAudio(func(string, []byte))` - receives internally encoded audio by request ID.
* `WithOnError(func(error))` - receives async session errors.
* `WithOnClose(func())` - runs when the session closes.

Egress options:

* `WithLiveKitEgress(config *LiveKitEgressConfig)` - stream output to LiveKit.
* `WithAgoraEgress(config *AgoraEgressConfig)` - stream output to Agora.

## Changelog

See [GitHub releases](https://github.com/spatius-ai/spatius-sdk-go/releases).
