Soniox

Full SDK reference

Full SDK reference.

API Reference

errors

SonioxError Objects

class SonioxError(Exception)

Base exception for the SDK.

SonioxValidationError Objects

class SonioxValidationError(SonioxError)

Raised when Pydantic input validation fails on the client side.

SonioxAPIError Objects

class SonioxAPIError(SonioxError)

Raised when the Soniox API replies with a non-2xx payload.

from_response

@classmethod
def from_response(cls, response: httpx.Response) -> SonioxAPIError

Parse an httpx.Response into a richer SDK error.

SonioxAuthenticationError Objects

class SonioxAuthenticationError(SonioxAPIError)

Authentication failures (401/403).

SonioxInvalidRequestError Objects

class SonioxInvalidRequestError(SonioxAPIError)

Invalid request payloads (400).

SonioxNotFoundError Objects

class SonioxNotFoundError(SonioxAPIError)

Resource not found.

SonioxConflictError Objects

class SonioxConflictError(SonioxAPIError)

Conflict or invalid state (e.g., delete while processing).

SonioxRateLimitError Objects

class SonioxRateLimitError(SonioxAPIError)

Rate limit (429).

SonioxServerError Objects

class SonioxServerError(SonioxAPIError)

5xx responses.

InvalidWebhookSignatureError Objects

class InvalidWebhookSignatureError(SonioxError)

Raised when a webhook signature cannot be validated.

SonioxRealtimeError Objects

class SonioxRealtimeError(SonioxError)

Errors raised by realtime workflows.

__init__

utils

stream_audio

def stream_audio(file: Path | str | BinaryIO | bytes,
                 *,
                 chunk_size_bytes: int = 4 * 1024) -> Iterator[bytes]

Yield fixed-size chunks from an audio source.

Supports bytes, file paths, or binary streams and slices them into chunk_size_bytes blocks for realtime transmission.

stream_audio_async

async def stream_audio_async(
        file: Path | str | BinaryIO | bytes,
        *,
        chunk_size_bytes: int = 4 * 1024) -> AsyncIterator[bytes]

Asynchronously yield fixed-size chunks from an audio source.

Mirrors stream_audio but produces an async iterator for later consumption.

throttle_audio

def throttle_audio(file: Path | str | BinaryIO | bytes,
                   *,
                   chunk_size_bytes: int = 4096,
                   delay_seconds: float = 0.0) -> Iterator[bytes]

Yield audio chunks at a regulated pace, optionally sleeping between yields.

throttle_audio_async

async def throttle_audio_async(
        file: Path | str | BinaryIO | bytes,
        *,
        chunk_size_bytes: int = 32 * 1024,
        delay_seconds: float = 0.0) -> AsyncIterator[bytes]

Async counterpart of throttle_audio, yielding chunks with optional delay.

render_tokens

def render_tokens(final_tokens: list[Token],
                  non_final_tokens: list[Token]) -> str

Build a human-friendly transcript from token metadata.

start_audio_thread

def start_audio_thread(session: RealtimeSTTSession,
                       chunks: bytes | Iterator[bytes],
                       *,
                       name: str | None = None,
                       daemon: bool = True) -> threading.Thread

Stream audio into the session on a background thread.

start_keep_alive_thread

def start_keep_alive_thread(
        session: RealtimeSTTSession,
        *,
        interval_seconds: float = 10.0,
        name: str | None = None,
        daemon: bool = True) -> tuple[threading.Thread, threading.Event]

Start a background thread that periodically sends keep-alives to the session.

Returns:

A tuple of (thread, stop_event). Setting stop_event will stop the loop.

keep_alive_async

async def keep_alive_async(session: AsyncRealtimeSTTSession,
                           *,
                           interval_seconds: float = 10.0,
                           stop_event: asyncio.Event | None = None) -> None

Async helper that repeatedly sends keep-alive messages until told to stop.

client

SonioxClient Objects

class SonioxClient(_BaseSonioxClient)

Synchronous Soniox REST client exposing API namespaces via httpx.

request

def request(method: str,
            path: str,
            *,
            params: Mapping[str, Any] | None = None,
            json: Any | None = None,
            data: Mapping[str, Any] | None = None,
            files: Mapping[str, Any] | None = None) -> httpx.Response

Perform a request against the configured Soniox REST endpoint.

close

def close() -> None

Close the underlying HTTP transport.

AsyncSonioxClient Objects

class AsyncSonioxClient(_BaseSonioxClient)

Asynchronous Soniox REST client exposing HTTP and realtime helpers.

request

async def request(method: str,
                  path: str,
                  *,
                  params: Mapping[str, Any] | None = None,
                  json: Any | None = None,
                  data: Mapping[str, Any] | None = None,
                  files: Mapping[str, Any] | None = None) -> httpx.Response

Perform a request against the configured Soniox REST endpoint.

aclose

async def aclose() -> None

Close any outstanding async HTTP connections.

types

types.common

Token Objects

class Token(BaseModel)

Token metadata emitted during realtime streaming transcriptions.

types.webhooks

WebhookAuthConfig Objects

class WebhookAuthConfig(BaseModel)

Configuration for webhook authentication headers.

WebhookEvent Objects

class WebhookEvent(BaseModel)

Basic webhook event metadata.

types.realtime

RealtimeEvent Objects

class RealtimeEvent(BaseModel)

Event payload received from the realtime STT websocket.

RealtimeSTTConfig Objects

class RealtimeSTTConfig(BaseModel)

Configuration for initiating a realtime transcription session.

RealtimeControlType Objects

class RealtimeControlType(str, Enum)

Control messages that can be sent over a realtime session.

RealtimeSessionOpenPayload Objects

class RealtimeSessionOpenPayload(BaseModel)

Event emitted when a realtime websocket session opens.

RealtimeSessionClosePayload Objects

class RealtimeSessionClosePayload(BaseModel)

Event emitted when a realtime websocket session closes.

RealtimeSessionFinishedPayload Objects

class RealtimeSessionFinishedPayload(BaseModel)

Event emitted when a realtime session finishes processing.

RealtimeSessionErrorPayload Objects

class RealtimeSessionErrorPayload(BaseModel)

Event emitted when a realtime session reports an error.

types.api

ApiErrorValidationError Objects

class ApiErrorValidationError(BaseModel)

Details a single validation error reported by the Soniox API.

ApiError Objects

class ApiError(BaseModel)

Structured representation of a non-2xx API response payload.

GetFilesPayload Objects

class GetFilesPayload(BaseModel)

Parameters accepted by the file listing endpoint.

File Objects

class File(BaseModel)

Metadata describing an uploaded file in the Soniox API.

GetFilesResponse Objects

class GetFilesResponse(BaseModel)

Paginated response returned when listing uploaded files.

UploadFilePayload Objects

class UploadFilePayload(BaseModel)

Optional metadata supplied at upload time.

GetTranscriptionsPayload Objects

class GetTranscriptionsPayload(BaseModel)

Parameters for listing transcription jobs.

StructuredContextGeneralItem Objects

class StructuredContextGeneralItem(BaseModel)

Single general context key/value pair for transcription context.

StructuredContextTranslationTerm Objects

class StructuredContextTranslationTerm(BaseModel)

Defines a translation term mapping used in structured context.

StructuredContext Objects

class StructuredContext(BaseModel)

Optional structured context provided to the transcription engine.

TranslationConfig Objects

class TranslationConfig(BaseModel)

Configuration describing how translation should be performed.

CreateTranscriptionPayload Objects

class CreateTranscriptionPayload(BaseModel)

Payload sent to create an asynchronous transcription job.

CreateTranscriptionConfig Objects

class CreateTranscriptionConfig(BaseModel)

Helper config used when building transcription payloads.

CreateTemporaryApiKeyPayload Objects

class CreateTemporaryApiKeyPayload(BaseModel)

Payload for requesting a temporary API key (e.g., websocket).

CreateTemporaryApiKeyResponse Objects

class CreateTemporaryApiKeyResponse(BaseModel)

Response data for a temp API key request.

Language Objects

class Language(BaseModel)

Represents a supported language for transcription or translation.

TranslationTarget Objects

class TranslationTarget(BaseModel)

Describes translation targets offered by a model.

Model Objects

class Model(BaseModel)

Describes a Soniox transcription model.

GetModelsResponse Objects

class GetModelsResponse(BaseModel)

Response returned when listing available models.

TranscriptionTranscript Objects

class TranscriptionTranscript(BaseModel)

Transcript data including the full text and tokens.

Transcription Objects

class Transcription(BaseModel)

Represents a transcription job tracked by Soniox.

GetTranscriptionsResponse Objects

class GetTranscriptionsResponse(BaseModel)

Paginated response for transcription listings.

api

api.webhooks

SonioxWebhooksAPI Objects

class SonioxWebhooksAPI()

verify_signature

def verify_signature(headers: Headers,
                     *,
                     auth: WebhookAuthConfig | None = None) -> None

Verify a webhook signature from headers.

Raises:

  • InvalidWebhookSignatureError - When the webhook signature cannot be validated.

unwrap

def unwrap(payload: str | bytes,
           headers: Headers,
           *,
           auth: WebhookAuthConfig | None = None) -> WebhookEvent

Validate and parse a webhook payload.

Returns a WebhookEvent.

Raises:

  • InvalidWebhookSignatureError - When the webhook signature cannot be validated.

webhook_payload

def webhook_payload(webhook_url: str,
                    *,
                    auth: WebhookAuthConfig | None = None) -> dict[str, str]

Return fields for webhook configuration when creating a transcription.

api.files

FilesAPI Objects

class FilesAPI()

list

def list(limit: int = 100, cursor: str | None = None) -> GetFilesResponse

List uploaded files.

Performs a GET request to /files with optional pagination.

Raises:

  • SonioxAPIError - When the API returns an error.

get

def get(file_id: str) -> File

Retrieve a file by ID.

Performs a GET request to /files/{file_id}.

Raises:

  • SonioxAPIError - When the API returns an error.

get_or_none

def get_or_none(file_id: str) -> File | None

Retrieve a file by ID.

Returns None if the file does not exist.

Raises:

  • SonioxAPIError - When the API returns an error.

delete

def delete(file_id: str) -> None

Delete a file by ID.

Performs a DELETE request to /files/{file_id}.

Raises:

  • SonioxAPIError - When the API returns an error.

delete_if_exists

def delete_if_exists(file_id: str) -> None

Delete a file by ID if it exists.

Ignores missing files.

Raises:

  • SonioxAPIError - When the API returns an error.

upload

def upload(file: BinaryIO | bytes | Path | str,
           *,
           filename: str | None = None,
           client_reference_id: str | None = None) -> File

Upload a file.

Performs a multipart POST request to /files.

Raises:

  • SonioxAPIError - When the API returns an error.

delete_all

def delete_all(*, limit: int = 100) -> None

Delete all files.

Iterates through all pages and deletes each file.

Raises:

  • SonioxAPIError - When the API returns an error.

api.async_files

AsyncFilesAPI Objects

class AsyncFilesAPI()

list

async def list(limit: int = 100,
               cursor: str | None = None) -> GetFilesResponse

List uploaded files.

Performs a GET request to /files with optional pagination.

Raises:

  • SonioxAPIError - When the API returns an error.

get

async def get(file_id: str) -> File

Retrieve a file by ID.

Performs a GET request to /files/{file_id}.

Raises:

  • SonioxAPIError - When the API returns an error.

get_or_none

async def get_or_none(file_id: str) -> File | None

Retrieve a file by ID.

Returns None if the file does not exist.

Raises:

  • SonioxAPIError - When the API returns an error.

delete

async def delete(file_id: str) -> None

Delete a file by ID.

Performs a DELETE request to /files/{file_id}.

Raises:

  • SonioxAPIError - When the API returns an error.

delete_if_exists

async def delete_if_exists(file_id: str) -> None

Delete a file by ID if it exists.

Ignores missing files.

Raises:

  • SonioxAPIError - When the API returns an error.

upload

async def upload(file: BinaryIO | bytes | Path | str,
                 *,
                 filename: str | None = None,
                 client_reference_id: str | None = None) -> File

Upload a file.

Performs a multipart POST request to /files.

Raises:

  • SonioxAPIError - When the API returns an error.

delete_all

async def delete_all(*, limit: int = 100) -> None

Delete all files.

Iterates through all pages and deletes each file.

Raises:

  • SonioxAPIError - When the API returns an error.

api.auth

AuthAPI Objects

class AuthAPI()

create_temporary_api_key

def create_temporary_api_key(
        *,
        usage_type: TemporaryApiKeyUsageType = "transcribe_websocket",
        expires_in_seconds: int = 5 * 60,
        client_reference_id: str | None = None
) -> CreateTemporaryApiKeyResponse

Create a temporary API key.

Performs a POST request to /auth/temporary-api-key.

Raises:

  • SonioxAPIError - When the API returns an error.

api.models

ModelsAPI Objects

class ModelsAPI()

list

def list() -> GetModelsResponse

List available models.

Performs a GET request to /models.

Raises:

  • SonioxAPIError - When the API returns an error.

api.async_webhooks

api._utils

normalize_file

def normalize_file(file: BinaryIO | bytes | Path | str,
                   filename: str | None = None) -> tuple[BinaryIO, str, bool]

Return (file-like, filename, should_close) tuple for upload.

api.async_auth

AsyncAuthAPI Objects

class AsyncAuthAPI()

create_temporary_api_key

async def create_temporary_api_key(
        *,
        usage_type: TemporaryApiKeyUsageType = "transcribe_websocket",
        expires_in_seconds: int = 5 * 60,
        client_reference_id: str | None = None
) -> CreateTemporaryApiKeyResponse

Create a temporary API key.

Performs a POST request to /auth/temporary-api-key.

Raises:

  • SonioxAPIError - When the API returns an error.

api.async_transcriptions

AsyncTranscriptionsAPI Objects

class AsyncTranscriptionsAPI()

list

async def list(limit: int = 100,
               cursor: str | None = None) -> GetTranscriptionsResponse

List transcriptions.

Performs a GET request to /transcriptions with optional pagination.

Raises:

  • SonioxAPIError - When the API returns an error.

delete_all

async def delete_all(*, limit: int = 100) -> None

Delete all transcriptions.

Iterates through all pages and deletes each transcription.

Raises:

  • SonioxAPIError - When the API returns an error.

create

async def create(
        *,
        model: str = DEFAULT_MODEL,
        file_id: str | None = None,
        audio_url: str | None = None,
        client_reference_id: str | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription.

Performs a POST request to /transcriptions.

Raises:

  • SonioxAPIError - When the API returns an error.

get

async def get(transcription_id: str) -> Transcription

Retrieve a transcription by ID.

Performs a GET request to /transcriptions/{transcription_id}.

Raises:

  • SonioxAPIError - When the API returns an error.

get_or_none

async def get_or_none(transcription_id: str) -> Transcription | None

Retrieve a transcription by ID.

Returns None if the transcription does not exist.

Raises:

  • SonioxAPIError - When the API returns an error.

delete

async def delete(transcription_id: str) -> None

Delete a transcription by ID.

Performs a DELETE request to /transcriptions/{transcription_id}.

Raises:

  • SonioxAPIError - When the API returns an error.

delete_if_exists

async def delete_if_exists(transcription_id: str) -> None

Delete a transcription by ID if it exists.

Ignores missing transcriptions.

Raises:

  • SonioxAPIError - When the API returns an error.

destroy

async def destroy(transcription_id: str) -> None

Delete a transcription and its associated uploaded file.

Raises:

  • SonioxAPIError - When the API returns an error.

get_transcript

async def get_transcript(transcription_id: str) -> TranscriptionTranscript

Retrieve the transcript for a transcription.

Performs a GET request to /transcriptions/{transcription_id}/transcript.

Raises:

  • SonioxAPIError - When the API returns an error.

wait

async def wait(transcription_id: str,
               *,
               interval_sec: float = 5.0,
               timeout_sec: float | None = None) -> Transcription

Poll a transcription until it leaves the queued or processing state.

Raises:

  • SonioxAPIError - When the API returns an error.
  • TimeoutError - Waiting for the transcription to finish exceeded timeout_sec.

transcribe_from_url

async def transcribe_from_url(
        *,
        model: str = DEFAULT_MODEL,
        audio_url: str,
        client_reference_id: str | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription from an audio URL.

Raises:

  • SonioxAPIError - When the API returns an error.

transcribe_from_file_id

async def transcribe_from_file_id(
        *,
        model: str = DEFAULT_MODEL,
        file_id: str,
        client_reference_id: str | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription from an existing uploaded file.

Raises:

  • SonioxAPIError - When the API returns an error.

transcribe_from_file

async def transcribe_from_file(
        *,
        model: str = DEFAULT_MODEL,
        file: BinaryIO | bytes | Path | str,
        filename: str | None = None,
        client_reference_id: str | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Upload a file and create a transcription from it.

Raises:

  • SonioxAPIError - When the API returns an error.

transcribe

async def transcribe(
        *,
        model: str = DEFAULT_MODEL,
        audio_url: str | None = None,
        file_id: str | None = None,
        file: BinaryIO | bytes | Path | str | None = None,
        filename: str | None = None,
        client_reference_id: str | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription from a file, file ID, or audio URL.

Validates mutually exclusive inputs before submission.

Raises:

  • SonioxAPIError - When the API returns an error.
  • SonioxValidationError - When the payload fails validation.

transcribe_file_with_webhook

async def transcribe_file_with_webhook(
        *,
        model: str = DEFAULT_MODEL,
        file: BinaryIO | bytes | Path | str,
        webhook_url: str,
        filename: str | None = None,
        client_reference_id: str | None = None,
        webhook_auth: WebhookAuthConfig | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Upload a file, configure a webhook, and start transcription.

Raises:

  • SonioxAPIError - When the API returns an error.

transcribe_and_wait

async def transcribe_and_wait(
        *,
        model: str = DEFAULT_MODEL,
        audio_url: str | None = None,
        file_id: str | None = None,
        file: BinaryIO | bytes | Path | str | None = None,
        filename: str | None = None,
        client_reference_id: str | None = None,
        delete_after: bool = False,
        wait_interval_sec: float = 5.0,
        wait_timeout_sec: float | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription and wait for completion.

Returns a Transcription object after it is completed. Optionally deletes the transcription and the uploaded file after completion.

Raises:

  • SonioxAPIError - When the API returns an error.
  • SonioxValidationError - When the payload fails validation.
  • TimeoutError - Waiting for the transcription to finish exceeded timeout_sec.

transcribe_and_wait_with_tokens

async def transcribe_and_wait_with_tokens(
    *,
    model: str = DEFAULT_MODEL,
    audio_url: str | None = None,
    file_id: str | None = None,
    file: BinaryIO | bytes | Path | str | None = None,
    filename: str | None = None,
    client_reference_id: str | None = None,
    delete_after: bool = False,
    wait_interval_sec: float = 5.0,
    wait_timeout_sec: float | None = None,
    config: CreateTranscriptionConfig | None = None
) -> TranscriptionTranscript

Create a transcription, wait for completion, and return the transcript.

Optionally deletes the transcription and uploaded file after completion.

Raises:

  • SonioxAPIError - When the API returns an error.
  • SonioxValidationError - When the payload fails validation.
  • TimeoutError - Waiting for the transcription to finish exceeded timeout_sec.

api.async_models

AsyncModelsAPI Objects

class AsyncModelsAPI()

list

async def list() -> GetModelsResponse

List available models.

Performs a GET request to /models.

Raises:

  • SonioxAPIError - When the API returns an error.

api.transcriptions

TranscriptionsAPI Objects

class TranscriptionsAPI()

list

def list(limit: int = 100,
         cursor: str | None = None) -> GetTranscriptionsResponse

List transcriptions.

Performs a GET request to /transcriptions with optional pagination.

Raises:

  • SonioxAPIError - When the API returns an error.

delete_all

def delete_all(*, limit: int = 100) -> None

Delete all transcriptions.

Iterates through all pages and deletes each transcription.

Raises:

  • SonioxAPIError - When the API returns an error.

create

def create(*,
           model: str = DEFAULT_MODEL,
           file_id: str | None = None,
           audio_url: str | None = None,
           client_reference_id: str | None = None,
           config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription.

Performs a POST request to /transcriptions.

Raises:

  • SonioxAPIError - When the API returns an error.

get

def get(transcription_id: str) -> Transcription

Retrieve a transcription by ID.

Performs a GET request to /transcriptions/{transcription_id}.

Raises:

  • SonioxAPIError - When the API returns an error.

get_or_none

def get_or_none(transcription_id: str) -> Transcription | None

Retrieve a transcription by ID.

Returns None if the transcription does not exist.

Raises:

  • SonioxAPIError - When the API returns an error.

delete

def delete(transcription_id: str) -> None

Delete a transcription by ID.

Performs a DELETE request to /transcriptions/{transcription_id}.

Raises:

  • SonioxAPIError - When the API returns an error.

delete_if_exists

def delete_if_exists(transcription_id: str) -> None

Delete a transcription by ID if it exists.

Ignores missing transcriptions.

Raises:

  • SonioxAPIError - When the API returns an error.

destroy

def destroy(transcription_id: str) -> None

Delete a transcription and its associated uploaded file.

Raises:

  • SonioxAPIError - When the API returns an error.

get_transcript

def get_transcript(transcription_id: str) -> TranscriptionTranscript

Retrieve the transcript for a transcription.

Performs a GET request to /transcriptions/{transcription_id}/transcript.

Raises:

  • SonioxAPIError - When the API returns an error.

wait

def wait(transcription_id: str,
         *,
         interval_sec: float = 5.0,
         timeout_sec: float | None = None) -> Transcription

Poll a transcription until it leaves the queued or processing state.

Raises:

  • SonioxAPIError - When the API returns an error.
  • TimeoutError - Waiting for the transcription to finish exceeded timeout_sec.

transcribe_from_url

def transcribe_from_url(
        *,
        model: str = DEFAULT_MODEL,
        audio_url: str,
        client_reference_id: str | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription from an audio URL.

Raises:

  • SonioxAPIError - When the API returns an error.

transcribe_from_file_id

def transcribe_from_file_id(
        *,
        model: str = DEFAULT_MODEL,
        file_id: str,
        client_reference_id: str | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription from an existing uploaded file.

Raises:

  • SonioxAPIError - When the API returns an error.

transcribe_from_file

def transcribe_from_file(
        *,
        model: str = DEFAULT_MODEL,
        file: BinaryIO | bytes | Path | str,
        filename: str | None = None,
        client_reference_id: str | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Upload a file and create a transcription from it.

Raises:

  • SonioxAPIError - When the API returns an error.

transcribe

def transcribe(
        *,
        model: str = DEFAULT_MODEL,
        audio_url: str | None = None,
        file_id: str | None = None,
        file: BinaryIO | bytes | Path | str | None = None,
        filename: str | None = None,
        client_reference_id: str | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription from a file, file ID, or audio URL.

Validates mutually exclusive inputs before submission.

Raises:

  • SonioxAPIError - When the API returns an error.
  • SonioxValidationError - When the payload fails validation.

transcribe_file_with_webhook

def transcribe_file_with_webhook(
        *,
        model: str = DEFAULT_MODEL,
        file: BinaryIO | bytes | Path | str,
        webhook_url: str,
        filename: str | None = None,
        client_reference_id: str | None = None,
        webhook_auth: WebhookAuthConfig | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Upload a file, configure a webhook, and start transcription.

Raises:

  • SonioxAPIError - When the API returns an error.

transcribe_and_wait

def transcribe_and_wait(
        *,
        model: str = DEFAULT_MODEL,
        audio_url: str | None = None,
        file_id: str | None = None,
        file: BinaryIO | bytes | Path | str | None = None,
        filename: str | None = None,
        client_reference_id: str | None = None,
        delete_after: bool = False,
        wait_interval_sec: float = 5.0,
        wait_timeout_sec: float | None = None,
        config: CreateTranscriptionConfig | None = None) -> Transcription

Create a transcription and wait for completion.

Returns a Transcription object after it is completed. Optionally deletes the transcription and the uploaded file after completion.

Raises:

  • SonioxAPIError - When the API returns an error.
  • SonioxValidationError - When the payload fails validation.
  • TimeoutError - Waiting for the transcription to finish exceeded timeout_sec.

transcribe_and_wait_with_tokens

def transcribe_and_wait_with_tokens(
    *,
    model: str = DEFAULT_MODEL,
    audio_url: str | None = None,
    file_id: str | None = None,
    file: BinaryIO | bytes | Path | str | None = None,
    filename: str | None = None,
    client_reference_id: str | None = None,
    delete_after: bool = False,
    wait_interval_sec: float = 5.0,
    wait_timeout_sec: float | None = None,
    config: CreateTranscriptionConfig | None = None
) -> TranscriptionTranscript

Create a transcription, wait for completion, and return the transcript.

Optionally deletes the transcription and uploaded file after completion.

Raises:

  • SonioxAPIError - When the API returns an error.
  • SonioxValidationError - When the payload fails validation.
  • TimeoutError - Waiting for the transcription to finish exceeded timeout_sec.

realtime

AsyncRealtimeAPI Objects

class AsyncRealtimeAPI()

Entrypoint for async realtime helpers on AsyncSonioxClient.

RealtimeAPI Objects

class RealtimeAPI()

Entrypoint for realtime helpers on SonioxClient.

realtime.stt

RealtimeSTTSession Objects

class RealtimeSTTSession()

Synchronous WebSocket session for a single real-time speech-to-text stream.

This class manages the full lifecycle of a real-time transcription session: connecting to the WebSocket endpoint, streaming audio data, receiving events, and gracefully closing the stream. A session is stateful and represents exactly one streaming interaction with the Soniox realtime API.

Instances are designed to be used as context managers.

__init__

def __init__(url: str, config: RealtimeSTTConfig) -> None

Create a new realtime STT session.

This does not open a network connection. The WebSocket connection is established when entering the context manager.

Arguments:

url: WebSocket URL for the realtime transcription endpoint. config: Configuration describing the audio format and transcription behavior for this session.

config

@property
def config() -> RealtimeSTTConfig

Return the configuration used to initialize this session.

__enter__

def __enter__() -> RealtimeSTTSession

Open the WebSocket connection and start the realtime session.

The session configuration is sent immediately after connecting. If any step fails, the connection is closed and a SonioxRealtimeError is raised.

Returns:

The active realtime session instance.

Raises:

SonioxRealtimeError: If the WebSocket connection or session initialization fails.

__exit__

def __exit__(_exc_type: type[BaseException] | None,
             _exc_value: BaseException | None,
             _traceback: TracebackType | None) -> None

Close the realtime session and release network resources.

This method is called automatically when exiting the context manager.

close

def close() -> None

Gracefully close the realtime session.

Sends a final empty message to signal end-of-stream, then closes the WebSocket connection. Calling this method multiple times is safe.

send_byte_chunk

def send_byte_chunk(chunk: bytes) -> None

Send a single chunk of raw audio bytes to the realtime stream.

The audio data must match the format declared in the session configuration (sample rate, channels, encoding).

Arguments:

chunk: Raw audio bytes to send.

Raises:

SonioxRealtimeError: If the session is not connected or the send operation fails.

send_bytes

def send_bytes(chunks: bytes | Iterator[bytes]) -> None

Send audio data to the realtime stream.

This method accepts either a single bytes object or an iterator yielding audio chunks. When an iterator is provided, a FINISH control message is sent automatically after all chunks have been transmitted.

Arguments:

chunks: Audio data as raw bytes or an iterator of byte chunks.

send_control_message

def send_control_message(control_type: RealtimeControlType) -> None

Send a control message to the realtime session.

Control messages modify the state of the stream, such as signaling end-of-audio or requesting finalization.

Arguments:

control_type: The type of control message to send.

Raises:

SonioxRealtimeError: If the session is not connected or the message cannot be sent.

send_finish

def send_finish() -> None

Signal that no more audio will be sent for this session.

send_keep_alive

def send_keep_alive() -> None

Send a keep-alive message to prevent the session from timing out.

send_finalize

def send_finalize() -> None

Finalize all outstanding non-final tokens while keeping the session open.

Subsequent tokens will be delivered with is_final=True.

recv_bytes

def recv_bytes() -> bytes

Receive a raw message from the WebSocket connection.

Returns:

The received message as bytes. An empty bytes object indicates that the connection has been closed.

parse_event

def parse_event(raw: str | bytes) -> RealtimeEvent

Parse a raw WebSocket message into a structured realtime event.

Arguments:

raw: Raw message payload received from the server.

Returns:

A validated RealtimeEvent instance.

last_message

@property
def last_message() -> RealtimeEvent | None

Return the most recently received realtime event, if any.

receive_event

def receive_event() -> RealtimeEvent | None

Receive and parse the next realtime event from the server.

Returns:

The next RealtimeEvent, or None if the connection has closed.

Raises:

SonioxRealtimeError: If the session is not connected.

receive_events

def receive_events() -> Iterator[RealtimeEvent]

Yield realtime events as they are received from the server.

Iteration stops automatically when the connection is closed.

handle_events

def handle_events(handler: Callable[[RealtimeEvent], None]) -> None

Receive realtime events and dispatch them to a handler callback.

Arguments:

handler: Callable invoked for each received RealtimeEvent.

RealtimeSTTClient Objects

class RealtimeSTTClient()

Factory for creating synchronous realtime speech-to-text sessions.

This class validates credentials and prepares session configuration, but does not itself manage WebSocket connections.

__init__

def __init__(client: SonioxClient) -> None

Create a realtime STT client bound to an existing API client.

Arguments:

client: Parent Soniox client providing configuration and credentials.

connect

def connect(*,
            config: RealtimeSTTConfig,
            api_key: str | None = None) -> RealtimeSTTSession

Create a new realtime STT session.

The returned session is not connected until entered as a context manager.

Arguments:

config: Realtime transcription configuration. api_key: Optional API key override. If not provided, the client's default API key is used.

Returns:

A new RealtimeSTTSession instance.

Raises:

SonioxValidationError: If no API key is available.

realtime.async_stt

AsyncRealtimeSTTSession Objects

class AsyncRealtimeSTTSession()

Asynchronous WebSocket session for a single real-time speech-to-text stream.

This class manages the full lifecycle of a real-time transcription session: connecting to the WebSocket endpoint, streaming audio data, receiving events, and gracefully closing the stream. A session is stateful and represents exactly one streaming interaction with the Soniox realtime API.

Instances are designed to be used as async context managers.

__init__

def __init__(url: str, config: RealtimeSTTConfig) -> None

Create a new realtime STT session.

This does not open a network connection. The WebSocket connection is established when entering the async context manager.

Arguments:

url: WebSocket URL for the realtime transcription endpoint. config: Configuration describing the audio format and transcription behavior for this session.

config

@property
def config() -> RealtimeSTTConfig

Return the configuration used to initialize this session.

__aenter__

async def __aenter__() -> AsyncRealtimeSTTSession

Open the WebSocket connection and start the realtime session.

The session configuration is sent immediately after connecting. If any step fails, the connection is closed and a SonioxRealtimeError is raised.

Returns:

The active realtime session instance.

Raises:

SonioxRealtimeError: If the WebSocket connection or session initialization fails.

__aexit__

async def __aexit__(_exc_type: type[BaseException] | None,
                    _exc_value: BaseException | None,
                    _traceback: TracebackType | None) -> None

Close the realtime session and release network resources.

This method is called automatically when exiting the async context manager.

close

async def close() -> None

Gracefully close the realtime session.

Sends a final empty message to signal end-of-stream, then closes the WebSocket connection. Calling this method multiple times is safe.

send_byte_chunk

async def send_byte_chunk(chunk: bytes) -> None

Send a single chunk of raw audio bytes to the realtime stream.

The audio data must match the format declared in the session configuration (sample rate, channels, encoding).

Arguments:

chunk: Raw audio bytes to send.

Raises:

SonioxRealtimeError: If the session is not connected or the send operation fails.

send_bytes

async def send_bytes(chunks: bytes | AsyncIterator[bytes]) -> None

Send audio data to the realtime stream.

This method accepts either a single bytes object or an iterator yielding audio chunks. When an iterator is provided, a FINISH control message is sent automatically after all chunks have been transmitted.

Arguments:

chunks: Audio data as raw bytes or an iterator of byte chunks.

send_control_message

async def send_control_message(control_type: RealtimeControlType) -> None

Send a control message to the realtime session.

Control messages modify the state of the stream, such as signaling end-of-audio or requesting finalization.

Arguments:

control_type: The type of control message to send.

Raises:

SonioxRealtimeError: If the session is not connected or the message cannot be sent.

send_finish

async def send_finish() -> None

Signal that no more audio will be sent for this session.

send_keep_alive

async def send_keep_alive() -> None

Send a keep-alive message to prevent the session from timing out.

send_finalize

async def send_finalize() -> None

Finalize all outstanding non-final tokens while keeping the session open.

Subsequent tokens will be delivered with is_final=True.

recv_bytes

async def recv_bytes() -> bytes

Receive a raw message from the WebSocket connection.

Returns:

The received message as bytes. An empty bytes object indicates that the connection has been closed.

parse_event

def parse_event(raw: str | bytes) -> RealtimeEvent

Parse a raw WebSocket message into a structured realtime event.

Arguments:

raw: Raw message payload received from the server.

Returns:

A validated RealtimeEvent instance.

last_message

@property
def last_message() -> RealtimeEvent | None

Return the most recently received realtime event, if any.

receive_event

async def receive_event() -> RealtimeEvent | None

Receive and parse the next realtime event from the server.

Returns:

The next RealtimeEvent, or None if the connection has closed.

Raises:

SonioxRealtimeError: If the session is not connected.

receive_events

async def receive_events() -> AsyncIterator[RealtimeEvent]

Yield realtime events as they are received from the server.

Iteration stops automatically when the connection is closed.

handle_events

async def handle_events(
        handler: Callable[[RealtimeEvent], Awaitable[None]]) -> None

Receive realtime events and dispatch them to a handler callback.

Arguments:

handler: Callable invoked for each received RealtimeEvent.

AsyncRealtimeSTTClient Objects

class AsyncRealtimeSTTClient()

Factory for creating asynchronous realtime speech-to-text sessions.

This class validates credentials and prepares session configuration, but does not itself manage WebSocket connections.

__init__

def __init__(client: AsyncSonioxClient) -> None

Create a realtime STT client bound to an existing API client.

Arguments:

client: Parent Soniox client providing configuration and credentials.

connect

def connect(*,
            config: RealtimeSTTConfig,
            api_key: str | None = None) -> AsyncRealtimeSTTSession

Create a new realtime STT session.

The returned session is not connected until entered as an async context manager.

Arguments:

config: Realtime transcription configuration. api_key: Optional API key override. If not provided, the client's default API key is used.

Returns:

A new AsyncRealtimeSTTSession instance.

Raises:

SonioxValidationError: If no API key is available.

On this page

API Reference
errors
SonioxError Objects
SonioxValidationError Objects
SonioxAPIError Objects
from_response
SonioxAuthenticationError Objects
SonioxInvalidRequestError Objects
SonioxNotFoundError Objects
SonioxConflictError Objects
SonioxRateLimitError Objects
SonioxServerError Objects
InvalidWebhookSignatureError Objects
SonioxRealtimeError Objects
__init__
utils
stream_audio
stream_audio_async
throttle_audio
throttle_audio_async
render_tokens
start_audio_thread
start_keep_alive_thread
keep_alive_async
client
SonioxClient Objects
request
close
AsyncSonioxClient Objects
request
aclose
types
types.common
Token Objects
types.webhooks
WebhookAuthConfig Objects
WebhookEvent Objects
types.realtime
RealtimeEvent Objects
RealtimeSTTConfig Objects
RealtimeControlType Objects
RealtimeSessionOpenPayload Objects
RealtimeSessionClosePayload Objects
RealtimeSessionFinishedPayload Objects
RealtimeSessionErrorPayload Objects
types.api
ApiErrorValidationError Objects
ApiError Objects
GetFilesPayload Objects
File Objects
GetFilesResponse Objects
UploadFilePayload Objects
GetTranscriptionsPayload Objects
StructuredContextGeneralItem Objects
StructuredContextTranslationTerm Objects
StructuredContext Objects
TranslationConfig Objects
CreateTranscriptionPayload Objects
CreateTranscriptionConfig Objects
CreateTemporaryApiKeyPayload Objects
CreateTemporaryApiKeyResponse Objects
Language Objects
TranslationTarget Objects
Model Objects
GetModelsResponse Objects
TranscriptionTranscript Objects
Transcription Objects
GetTranscriptionsResponse Objects
api
api.webhooks
SonioxWebhooksAPI Objects
verify_signature
unwrap
webhook_payload
api.files
FilesAPI Objects
list
get
get_or_none
delete
delete_if_exists
upload
delete_all
api.async_files
AsyncFilesAPI Objects
list
get
get_or_none
delete
delete_if_exists
upload
delete_all
api.auth
AuthAPI Objects
create_temporary_api_key
api.models
ModelsAPI Objects
list
api.async_webhooks
api._utils
normalize_file
api.async_auth
AsyncAuthAPI Objects
create_temporary_api_key
api.async_transcriptions
AsyncTranscriptionsAPI Objects
list
delete_all
create
get
get_or_none
delete
delete_if_exists
destroy
get_transcript
wait
transcribe_from_url
transcribe_from_file_id
transcribe_from_file
transcribe
transcribe_file_with_webhook
transcribe_and_wait
transcribe_and_wait_with_tokens
api.async_models
AsyncModelsAPI Objects
list
api.transcriptions
TranscriptionsAPI Objects
list
delete_all
create
get
get_or_none
delete
delete_if_exists
destroy
get_transcript
wait
transcribe_from_url
transcribe_from_file_id
transcribe_from_file
transcribe
transcribe_file_with_webhook
transcribe_and_wait
transcribe_and_wait_with_tokens
realtime
AsyncRealtimeAPI Objects
RealtimeAPI Objects
realtime.stt
RealtimeSTTSession Objects
__init__
config
__enter__
__exit__
close
send_byte_chunk
send_bytes
send_control_message
send_finish
send_keep_alive
send_finalize
recv_bytes
parse_event
last_message
receive_event
receive_events
handle_events
RealtimeSTTClient Objects
__init__
connect
realtime.async_stt
AsyncRealtimeSTTSession Objects
__init__
config
__aenter__
__aexit__
close
send_byte_chunk
send_bytes
send_control_message
send_finish
send_keep_alive
send_finalize
recv_bytes
parse_event
last_message
receive_event
receive_events
handle_events
AsyncRealtimeSTTClient Objects
__init__
connect