soulbits

package module
v0.0.0-...-9dc48fe Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Soulbits API Client — Go

First-party Go client for the Soulbits Cloud Platform REST API.

Installation

go get github.com/harmony-ai-solutions/soulbits-api-client-go

Quick Start

API Key Auth (server-side)
package main

import (
    "context"
    "fmt"
    "log"

    soulbits "github.com/harmony-ai-solutions/soulbits-api-client-go"
)

func main() {
    client, err := soulbits.New(&soulbits.Config{
        APIKey: "sb_cloud_your_api_key_here",
    })
    if err != nil {
        log.Fatal(err)
    }

    models, err := client.ListModels(context.Background(), nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Available models: %d\n", len(models))
}
PASETO Auth (user-facing)
client, err := soulbits.New(&soulbits.Config{
    PasetoToken:  "v4.local.xxx...",
    RefreshToken: "opaque_refresh_token",
})
Multi-Host Architecture

The client automatically routes requests to the correct host:

Host Operations
cloud.soulbits.app Auth, account, API keys, devices, session, subscription
api.soulbits.app Chat, embeddings, rerank, TTS, STT, VAD, voice/audio conversion

Usage Examples

Chat (OpenAI-compatible, non-streaming)
resp, err := client.Chat(ctx, &gen.ChatCompletionRequest{
    Model: "qwen-35-9b",
    Messages: []gen.ChatMessage{
        {Role: "user", Content: "Hello!"},
    },
})
Text Embeddings
resp, err := client.Embed(ctx, &gen.EmbeddingRequest{
    Model: "qwen3-embed-4b",
    Input: "Hello world",
})
TTS (Harmony Speech Engine)
audioBytes, _ := base64.StdEncoding.DecodeString(voiceSample)
resp, err := client.TTS(ctx, &gen.TTSRequest{
    Model: "kitten-tts-mini",
    Input: "Hello from Soulbits",
    Mode:  gen.SingleSpeakerTts,
})
Cloud Session Data Purge

DeleteSessionData starts a purge of the authenticated user's cloud-side engine data: it hard-kills any live session, deletes every S3 version, the beat schedule, and the DEK — all in the background. It is idempotent and destructive — the request requires Confirm: "DELETE".

The purge is asynchronous: DeleteSessionData returns immediately with status=in_progress and a request_id (via result.RequestID()), and never completes synchronously. Poll DeleteSessionDataStatus with that request_id until the terminal outcome — status=deleted (with the S3 / beat / DEK counters) or status=failed (unblocked, but deletion not guaranteed — retry the delete). status=none means nothing running or remembered.

result, err := client.DeleteSessionData(ctx, soulbits.DeleteSessionDataRequest{
    Confirm: "DELETE",
})
if err != nil {
    var confReq *soulbits.ConfirmationRequiredError
    var snapBusy *soulbits.SnapshotBusyError
    switch {
    case errors.As(err, &confReq):
        // 400 — Confirm must be "DELETE".
    case errors.As(err, &snapBusy):
        // 409 — snapshot lease busy, retry after snapBusy.RetryAfterMs.
    default:
        // Other API errors.
    }
} else if result.IsInProgress() {
    // 202/200 in_progress — purge accepted, poll for the outcome:
    status, err := client.DeleteSessionDataStatus(ctx)
    // status.IsInProgress() / IsDeleted() / IsFailed() / IsNone()
    // status.Deleted() exposes ObjectsDeleted, VersionsDeleted, BeatsRemoved, DekDeleted.
}

While a purge is in flight, ConnectSession returns a *PurgeInProgressError (409 purge_in_progress), and the connection poll loop treats that as terminal.

Authentication
// Login
token, err := client.Login(ctx, "user@example.com", "password")

// Refresh (PASETO only)
newToken, err := client.Refresh(ctx)

// Register
msg, err := client.Register(ctx, "user@example.com", "password", nil)

Regenerating from the OpenAPI Spec

# Install the generator (one time)
go install github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest

# Regenerate
go generate ./...

The openapi.yaml is the source of truth. Generated code lives in gen/client.go and is committed to the repo.

Development

go generate ./...   # regenerate from spec
go build ./...      # compile
go test ./...       # run tests (no network required)
go vet ./...        # static analysis

License

Apache 2.0 — see LICENSE.

Documentation

Overview

Package soulbits provides a first-party Go client for the Soulbits API.

The Soulbits API spans two REST hosts:

  • Cloud API (cloud.soulbits.app): authentication, account, API keys, session lifecycle, subscription, and OpenAPI spec download.
  • Inference API (api.soulbits.app): LLM chat, text embeddings, rerank, TTS, STT, VAD, speaker embedding, audio/voice conversion.

Two auth methods are supported:

  • API Key (sb_cloud_* prefix): long-lived, best for programmatic access.
  • PASETO v4.local token: refreshable, best for user-facing sessions.

The client automatically routes requests to the correct host based on the operation and injects the configured Bearer token. PASETO tokens are automatically refreshed on 401 with single-flight semantics (concurrent 401s trigger only one refresh call).

Generation

The request/response types and HTTP client bindings in the gen/ subpackage are generated from openapi.yaml via oapi-codegen. To regenerate:

go generate ./...

Embedding the spec

The OpenAPI 3.0.3 specification is embedded in the binary. Call Spec() to retrieve the raw YAML bytes for tooling and testing.

Package soulbits provides a first-party Go client for the Soulbits API.

Index

Constants

View Source
const (
	DefaultCloudBaseURL     = "https://beta.cloud.soulbits.app"
	DefaultInferenceBaseURL = "https://beta.api.soulbits.app"
)

Default base URLs for the Soulbits API (beta environment).

Variables

This section is empty.

Functions

func Spec

func Spec() []byte

Spec returns the raw OpenAPI 3.0.3 specification YAML bytes.

Types

type APIError

type APIError struct {
	StatusCode int
	Code       string // error code from the API ("rate_limit", "quota_exceeded", etc.)
	Message    string // human-readable message

	// Optional fields present on 402/504 errors
	UpgradeURL           *string
	CurrentTier          *string
	RequiredTier         *string
	SoulCreditsAvailable *int
	TaskID               *string
}

APIError represents an error returned by the Soulbits API. It implements the error interface and supports errors.As for type checking.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) IsForbidden

func (e *APIError) IsForbidden() bool

func (*APIError) IsNotFound

func (e *APIError) IsNotFound() bool

func (*APIError) IsRateLimited

func (e *APIError) IsRateLimited() bool

func (*APIError) IsStatusCode

func (e *APIError) IsStatusCode(code int) bool

IsStatusCode returns true if the error has the given HTTP status code.

func (*APIError) IsTimeout

func (e *APIError) IsTimeout() bool

func (*APIError) IsUnauthorized

func (e *APIError) IsUnauthorized() bool

Common status code checks.

type APIKeyAuth

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

APIKeyAuth authenticates using a long-lived sb_cloud_* API key.

func NewAPIKeyAuth

func NewAPIKeyAuth(apiKey string) *APIKeyAuth

NewAPIKeyAuth creates a new API key auth strategy.

func (*APIKeyAuth) IsPASETO

func (a *APIKeyAuth) IsPASETO() bool

func (*APIKeyAuth) Token

func (a *APIKeyAuth) Token() string

type AuthStrategy

type AuthStrategy interface {
	// Token returns the current Bearer token value.
	Token() string

	// IsPASETO returns true if this strategy uses PASETO tokens (supports refresh).
	IsPASETO() bool
}

AuthStrategy represents a method of authentication for the Soulbits API.

type Client

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

Client is the high-level Soulbits API client.

Create a new client with New(), then use the methods on the returned *Client to interact with the API. All public methods accept a context.Context as the first argument.

Internally the Client uses two oapi-codegen generated clients:

  • cloudGen routes to the Cloud API (auth, account, keys, session, subscription).
  • inferGen routes to the Inference API (chat, embeddings, audio, etc.).

Auth is injected via an http.RoundTripper wrapping the underlying http.Client transport — the generated security-scope helpers (gen.ApiKeyScopes / gen.PasetoScopes) are NOT used; the RoundTripper sets the Authorization header on every outgoing request.

func New

func New(cfg *Config) (*Client, error)

New creates a new Soulbits API Client.

If the config provides an AuthStrategy, it is used verbatim and the string credential fields below are ignored. Otherwise, if the config provides an APIKey, API key auth is used. Otherwise, if a PasetoToken is provided, PASETO auth is used. If none are set, the client is created without auth (suitable for public endpoints like model listing and subscription tiers).

The config is modified in place to fill defaults; the caller should not reuse it after passing to New.

Auth wiring: the generated gen.ClientWithResponses receives an http.Client whose transport is wrapped with the auth round-tripper. The round-tripper injects the Authorization: Bearer header on every outgoing request and handles PASETO 401 auto-refresh. The generated security-scope context keys (gen.ApiKeyScopes / gen.PasetoScopes) are NOT used — all auth flows through the transport layer instead.

func (*Client) AppleSignIn

func (c *Client) AppleSignIn(ctx context.Context, identityToken string) (*gen.TokenResponse, error)

AppleSignIn validates an Apple identity_token (native/iOS).

func (*Client) AppleSignInWeb

func (c *Client) AppleSignInWeb(ctx context.Context, code, redirectURI string) (*gen.TokenResponse, error)

AppleSignInWeb exchanges an authorization code for a token (web OAuth code flow).

func (*Client) ApproveDevice

func (c *Client) ApproveDevice(ctx context.Context, token string) (string, error)

ApproveDevice redeems the high-entropy approval token from the emailed approval button URL and returns the approved device ID. The authenticated session user must match the user the token was issued for.

Error mapping (all returned as *APIError):

  • 401 — invalid or expired token
  • 403 — token belongs to another account
  • 429 — approval attempt lockout (check APIError.IsRateLimited)

func (*Client) AudioConvert

func (c *Client) AudioConvert(ctx context.Context, req *gen.AudioConversionRequest) (*gen.AudioDataResponse, error)

AudioConvert converts/enhances audio (e.g. denoising via VoiceFixer).

func (*Client) Auth

func (c *Client) Auth() AuthStrategy

Auth returns the client's auth strategy, or nil if no auth is configured.

func (*Client) ChangePassword

func (c *Client) ChangePassword(ctx context.Context, oldPassword, newPassword string) (*gen.Message, error)

ChangePassword changes the current user's password. Writes a Valkey cutoff that forces re-login everywhere.

func (*Client) Chat

Chat sends a chat completion request to the Inference API. The response is always non-streaming (stream:true is silently ignored by the gateway).

func (*Client) Config

func (c *Client) Config() *Config

Config returns the client's configuration.

func (*Client) ConfirmPasswordReset

func (c *Client) ConfirmPasswordReset(ctx context.Context, token, newPassword string) (*gen.Message, error)

ConfirmPasswordReset confirms a password reset with a token and new password.

func (*Client) CreateAPIKey

func (c *Client) CreateAPIKey(ctx context.Context, name *string) (*gen.APIKeyCreated, error)

CreateAPIKey creates a new API key. The full key is returned only once. API keys CANNOT create/list/revoke other API keys (PASETO auth required).

func (*Client) CreateDeviceConnectSession

func (c *Client) CreateDeviceConnectSession(ctx context.Context, deviceID string, deviceName *string, platform *gen.DeviceConnectSessionRequestPlatform) (*gen.DeviceConnectSessionResponse, error)

CreateDeviceConnectSession starts the portal-mediated engine sign-in flow. Public (the engine is not authenticated yet): the server mints an unguessable connect_id plus a once-shown 256-bit session_secret and returns the portal URL the engine should open in the system browser. Poll GetDeviceConnectSession with the returned secret until the user allows it.

deviceName and platform are optional; pass a nil platform to let the server default it to "web".

func (*Client) Embed

Embed creates text embeddings using the Inference API.

func (*Client) EnrollDeviceWithGrant

func (c *Client) EnrollDeviceWithGrant(ctx context.Context, grant, deviceID string, deviceName *string, platform *gen.DeviceEnrollRequestPlatform) (*gen.TokenResponse, error)

EnrollDeviceWithGrant redeems an enrollment grant for the NEW device's own device-scoped session. Public: no account auth is sent — the grant IS the credential. deviceName and platform are optional metadata; pass a nil platform to let the server default it to "android".

func (*Client) GetDeviceAuthorizationStatus

func (c *Client) GetDeviceAuthorizationStatus(ctx context.Context, deviceID string) (*gen.DeviceAuthorizationStatus, error)

GetDeviceAuthorizationStatus returns the poll state for the device auth flow. The app polls until Authorized is true.

func (*Client) GetDeviceConnectSession

func (c *Client) GetDeviceConnectSession(ctx context.Context, connectID, sessionSecret string) (*gen.DeviceConnectStatusResponse, error)

GetDeviceConnectSession polls a connect session using the once-shown session_secret as the Bearer credential. Status is one of pending|approved|consumed|expired. The token pair is populated ONLY on the approved transition and returned exactly once (the server marks the row consumed in the same statement), so persist it immediately.

Use an UNauthenticated client (no API key / PASETO) for this call: the secret is set as the Authorization header and, when account auth is configured, the auth round-tripper would overwrite it (see transport.go).

func (*Client) GetMySubscription

func (c *Client) GetMySubscription(ctx context.Context) (*gen.SubscriptionMe, error)

GetMySubscription returns the current user's subscription. Defaults to "free" if no subscription exists.

func (*Client) GoogleSignIn

func (c *Client) GoogleSignIn(ctx context.Context, idToken string) (*gen.TokenResponse, error)

GoogleSignIn validates a Google id_token (native/Android).

func (*Client) GoogleSignInWeb

func (c *Client) GoogleSignInWeb(ctx context.Context, authCode, redirectURI string, codeVerifier *string) (*gen.TokenResponse, error)

GoogleSignInWeb exchanges an authorization code for a token (web OAuth code flow).

func (*Client) ImageGen

func (c *Client) ImageGen(ctx context.Context, req *gen.ImageGenerationRequest) error

ImageGen generates images. Deprecated — no worker is currently deployed. Attempts will likely result in a 503 or gateway timeout.

func (*Client) LinkApple

func (c *Client) LinkApple(ctx context.Context, identityToken string) (*gen.Message, error)

LinkApple links an Apple identity to the current account.

func (*Client) LinkGoogle

func (c *Client) LinkGoogle(ctx context.Context, idToken string) (*gen.Message, error)

LinkGoogle links a Google identity to the current account.

func (*Client) ListAPIKeys

func (c *Client) ListAPIKeys(ctx context.Context) ([]gen.APIKeyListItem, error)

ListAPIKeys lists all API keys for the current user. The raw key value is never returned — only the prefix for identification.

func (*Client) ListDevices

func (c *Client) ListDevices(ctx context.Context) ([]gen.DeviceListItem, error)

ListDevices lists the devices registered to the current user.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context, filter *ModelFilter) ([]gen.ModelEntry, error)

ListModels returns all active models from the catalog. Supports optional filters by model type and modalities.

func (*Client) ListTiers

func (c *Client) ListTiers(ctx context.Context) ([]gen.Tier, error)

ListTiers lists all subscription tiers. Public endpoint — no auth required.

func (*Client) Login

func (c *Client) Login(ctx context.Context, email, password string) (*gen.TokenResponse, error)

Login authenticates with email and password. Returns a token pair. The account must have email_verified=true.

func (*Client) Logout

func (c *Client) Logout(ctx context.Context, refreshToken *string) (*gen.Message, error)

Logout revokes refresh tokens and writes a PASETO cutoff. If refreshToken is provided, only that token is revoked; otherwise all are.

func (*Client) Me

func (c *Client) Me(ctx context.Context) (*gen.UserProfile, error)

Me returns the current user's profile.

func (*Client) MintEnrollmentGrant

func (c *Client) MintEnrollmentGrant(ctx context.Context, deviceID string) (*gen.EnrollmentGrantResponse, error)

MintEnrollmentGrant mints a short-lived, single-use delegated-enrollment grant from an already-authorized device (deviceID is the MINTING device). The opaque grant is returned ONCE; only its SHA-256 is stored server-side. Requires account auth (device-scoped session or interactive/PASETO).

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context) (*gen.TokenResponse, error)

Refresh refreshes the PASETO token using the stored refresh token. This is only available when the client was configured with a PasetoAuth strategy. If using API key auth, this method will return an error.

func (*Client) Register

func (c *Client) Register(ctx context.Context, email, password string, displayName *string) (*gen.Message, error)

Register creates a new account. Returns 202 Accepted on success (email verification sent). No token is returned at this stage.

func (*Client) RegisterDevice

func (c *Client) RegisterDevice(ctx context.Context, deviceID string, platform gen.RegisterDeviceRequestPlatform, pushToken *string) (*gen.Device, error)

RegisterDevice registers (or refreshes) a client device install.

A new push token refreshes the existing registration. Pass a nil pushToken to clear push registration. Devices must complete the email auth-code flow (RequestDeviceAuthCode / VerifyDeviceAuthCode) before cloud sessions can be provisioned for them — see ConnectSession (403 device_authorization_required).

func (*Client) RequestDeviceAuthCode

func (c *Client) RequestDeviceAuthCode(ctx context.Context, deviceID string) error

RequestDeviceAuthCode starts the D-DEV-04 device authorization flow: the server emails the 6-digit code plus the approval button link and returns 202. The caller should then poll GetDeviceAuthorizationStatus until the device is authorized (or the user manually enters the code via VerifyDeviceAuthCode).

func (*Client) RequestPasswordReset

func (c *Client) RequestPasswordReset(ctx context.Context, email string) (*gen.Message, error)

RequestPasswordReset requests a password reset email.

func (*Client) Rerank

func (c *Client) Rerank(ctx context.Context, req *gen.RerankRequest) (*gen.RerankResponse, error)

Rerank ranks documents by their relevance to a query.

func (*Client) ResendVerification

func (c *Client) ResendVerification(ctx context.Context, email string) (*gen.Message, error)

ResendVerification resends the verification email. Per-user 60s cooldown.

func (*Client) RevokeAPIKey

func (c *Client) RevokeAPIKey(ctx context.Context, id string) error

RevokeAPIKey revokes an API key by ID. Idempotent.

func (*Client) RevokeDevice

func (c *Client) RevokeDevice(ctx context.Context, deviceID string) error

RevokeDevice revokes a device's authorization and removes it from the user's device list. Idempotent — revoking an unknown device returns 404.

func (*Client) STT

func (c *Client) STT(ctx context.Context, req *gen.STTRequest) (*gen.STTResponse, error)

STT transcribes audio to text using the Harmony Speech Engine.

func (*Client) SpeakerEmbed

func (c *Client) SpeakerEmbed(ctx context.Context, req *gen.SpeakerEmbedRequest) (*gen.AudioDataResponse, error)

SpeakerEmbed creates a speaker embedding from an audio sample. The returned AudioDataResponse.Data contains the base64-encoded embedding.

func (*Client) String

func (c *Client) String() string

String returns a human-readable description of the client.

func (*Client) TTS

TTS synthesises speech from text using the Harmony Speech Engine.

func (*Client) UnlinkApple

func (c *Client) UnlinkApple(ctx context.Context) error

UnlinkApple unlinks the Apple identity from the current account.

func (*Client) UnlinkGoogle

func (c *Client) UnlinkGoogle(ctx context.Context) error

UnlinkGoogle unlinks the Google identity from the current account.

func (*Client) UpdateProfile

func (c *Client) UpdateProfile(ctx context.Context, displayName string) (*gen.UserProfile, error)

UpdateProfile updates the current user's profile (only display_name is mutable).

func (*Client) VAD

func (c *Client) VAD(ctx context.Context, req *gen.VADRequest) (*gen.VADResponse, error)

VAD performs voice activity detection on audio.

func (*Client) VerifyDeviceAuthCode

func (c *Client) VerifyDeviceAuthCode(ctx context.Context, deviceID, code string) error

VerifyDeviceAuthCode verifies the 6-digit email auth code and marks the device authorized. Returns nil on success (200).

func (*Client) VerifyEmail

func (c *Client) VerifyEmail(ctx context.Context, token string) (*gen.TokenResponse, error)

VerifyEmail verifies an email address with a verification token. Returns a token pair on success.

func (*Client) Versions

func (c *Client) Versions(ctx context.Context) (*gen.VersionsResponse, error)

Versions lists available Harmony Link image versions.

Retained after the session-hosting retirement (phase 6-1): the `/v1/versions` endpoint is not a session-plane route and remains part of the contract. The rest of the former session facade (connect/disconnect/ connected/data-purge) was removed with the `/v1/session/*` paths.

func (*Client) VoiceConvert

func (c *Client) VoiceConvert(ctx context.Context, req *gen.VoiceConversionRequest) (*gen.AudioDataResponse, error)

VoiceConvert converts the voice in source audio to sound like a target speaker.

type Config

type Config struct {
	// CloudBaseURL is the base URL for the Cloud API (auth, account, keys,
	// session, subscription). Defaults to https://beta.cloud.soulbits.app.
	CloudBaseURL string

	// InferenceBaseURL is the base URL for the Inference API (chat,
	// embeddings, rerank, audio). Defaults to https://beta.api.soulbits.app.
	InferenceBaseURL string

	// APIKey is an sb_cloud_* API key for Bearer authentication.
	// If set, it takes precedence over PasetoToken.
	APIKey string

	// PasetoToken is a v4.local.* PASETO token for Bearer authentication.
	PasetoToken string

	// RefreshToken is the opaque refresh token used by the auto-refresh
	// transport. Required for PASETO token refresh on 401.
	RefreshToken string

	// AuthStrategy, when non-nil, is used verbatim as the auth strategy and
	// takes precedence over APIKey/PasetoToken/RefreshToken. Use this to
	// inject a dynamic credential source (resolved per request via
	// authRoundTripper). When nil, behavior is identical to previous versions.
	AuthStrategy AuthStrategy

	// HTTPClient is the HTTP client used for API requests.
	// If nil, http.DefaultClient is used.
	HTTPClient *http.Client
}

Config configures a Soulbits API Client. All fields are optional; sensible defaults are used when omitted.

type ModelFilter

type ModelFilter struct {
	// ModelType filters by exact model type.
	// Valid values: llm, tts, stt, vad, embeddings, rerank, voice_embed,
	// audio_conversion, voice_conversion.
	ModelType gen.ModelEntryModelType

	// InputModalities is a superset filter — model must accept ALL listed
	// input modalities (e.g. ["text", "image"]).
	InputModalities []string

	// OutputModalities is a superset filter — model must emit ALL listed
	// output modalities.
	OutputModalities []string
}

ModelFilter filters the model catalog.

func (*ModelFilter) Validate

func (f *ModelFilter) Validate() error

Validate returns an error if the filter has invalid values.

type PasetoAuth

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

PasetoAuth authenticates using a PASETO v4.local token with automatic refresh on 401. Refresh is single-flight: concurrent 401s trigger only one refresh call; all waiters retry with the fresh token.

func NewPasetoAuth

func NewPasetoAuth(pasetoToken, refreshToken string, httpClient *http.Client, cloudBaseURL string) *PasetoAuth

NewPasetoAuth creates a new PASETO auth strategy with auto-refresh.

func (*PasetoAuth) IsPASETO

func (p *PasetoAuth) IsPASETO() bool

func (*PasetoAuth) Refresh

func (p *PasetoAuth) Refresh(ctx context.Context) error

Refresh performs a single-flight token refresh. If a refresh is already in flight, it waits for that one to complete and returns its result.

func (*PasetoAuth) RefreshToken

func (p *PasetoAuth) RefreshToken() string

RefreshToken returns the current refresh token value.

func (*PasetoAuth) Token

func (p *PasetoAuth) Token() string

Directories

Path Synopsis
Package gen provides primitives to interact with the openapi HTTP API.
Package gen provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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