Skip to main content

fishaudio.core.websocket_options

WebSocket-level options for WebSocket connections.

WebSocketOptions Objects

Options for configuring WebSocket connections. All options except additional_headers are passed directly to httpx_ws’s connect_ws/aconnect_ws functions. For complete documentation, see https://frankie567.github.io/httpx-ws/reference/httpx_ws/ Attributes:
  • keepalive_ping_timeout_seconds - Maximum delay the client will wait for an answer to its Ping event. If the delay is exceeded, WebSocketNetworkError will be raised and the connection closed. Default: 20 seconds.
  • keepalive_ping_interval_seconds - Interval at which the client will automatically send a Ping event to keep the connection alive. Set to None to disable this mechanism. Default: 20 seconds.
  • max_message_size_bytes - Message size in bytes to receive from the server.
  • Default - 65536 bytes (64 KiB).
  • queue_size - Size of the queue where received messages will be held until they are consumed. If the queue is full, the client will stop receiving messages from the server until the queue has room available. Default: 512.
  • additional_headers - Extra headers to send on the WebSocket handshake, for example {"traceparent": ...}. They are merged as RequestOptions.additional_headers are on an HTTP call: an Authorization here replaces the API key and a User-Agent is appended to the SDK’s own, in any casing; each is sent once, and with two spellings the last one given is used. model is always the method’s argument. The dict is not modified.
Notes: Descriptions of the httpx_ws options adapted from httpx_ws documentation.

to_httpx_ws_kwargs

Convert to kwargs dict for httpx_ws aconnect_ws/connect_ws.

fishaudio.core._sse

Minimal Server-Sent Events decoder.

ServerSentEvent Objects

One dispatched SSE event.

SSEDecoder Objects

Incrementally decode a Server-Sent Events byte stream. Feed raw response bytes with feed(); each call returns the events that were completed by those bytes. Lines end with CRLF, LF or CR, the three endings the SSE specification allows; other Unicode line separators stay inside the payload. An event left unterminated when the stream ends is dropped, as the specification requires.

feed

Add bytes from the stream and return the events they complete.

fishaudio.core.omit

OMIT sentinel for distinguishing None from not-provided parameters.

fishaudio.core.client_wrapper

HTTP client wrapper for managing requests and authentication.

PRODUCT

The SDK’s product, fish-audio-<language>/<version>: the format every Fish Audio SDK sends, so the API can tell which SDK and version made a request.

build_user_agent

Return fish-audio-python/<version> (python <python version>; <os>). Only the runtime, its version and the OS family are included: nothing that identifies a person or machine.

USER_AGENT

The User-Agent the SDK sends, computed once at import, e.g. fish-audio-python/1.6.0 (python 3.12.1; linux).

user_agent

Return the User-Agent to send: the SDK’s own, then caller if set. A caller’s value is appended after the SDK’s product and runtime comment rather than allowed to replace them, so an app can name itself without hiding which SDK made the request. A value that already starts with the SDK’s User-Agent is not doubled.

BaseClientWrapper Objects

Base wrapper with shared logic for sync/async clients.

get_headers

Build headers including authentication and user agent. A name in additional_headers replaces the SDK’s header of that name whatever its case, so the two are never sent side by side. The exception is User-Agent: one in additional_headers (any casing), or else one set on a user-supplied httpx client, is appended to the SDK’s own. Authorization and User-Agent are each sent once: given in two spellings, the last one given is used.

ClientWrapper Objects

Wrapper for httpx.Client that handles authentication and error handling.

request

Make an HTTP request with error handling. Arguments:
  • method - HTTP method (GET, POST, etc.)
  • path - API endpoint path
  • request_options - Optional request-level overrides
  • stream - If True, return as soon as the response headers arrive and leave the body unread. The caller must consume it with iter_bytes() and then call close() on the response.
  • **kwargs - Additional arguments to pass to httpx.request
Returns: httpx.Response object Raises:
  • APIError - On non-2xx responses

client

Get underlying httpx.Client for advanced usage (e.g., WebSockets).

close

Close the HTTP client.

AsyncClientWrapper Objects

Wrapper for httpx.AsyncClient that handles authentication and error handling.

request

Make an async HTTP request with error handling. Arguments:
  • method - HTTP method (GET, POST, etc.)
  • path - API endpoint path
  • request_options - Optional request-level overrides
  • stream - If True, return as soon as the response headers arrive and leave the body unread. The caller must consume it with aiter_bytes() and then call aclose() on the response.
  • **kwargs - Additional arguments to pass to httpx.request
Returns: httpx.Response object Raises:
  • APIError - On non-2xx responses

client

Get underlying httpx.AsyncClient for advanced usage (e.g., WebSockets).

close

Close the HTTP client.

fishaudio.core.request_options

Request-level options for API calls.

RequestOptions Objects

Options that can be provided on a per-request basis to override client defaults. Attributes:
  • timeout - Override the client’s default timeout (in seconds)
  • max_retries - Override the client’s default max retries
  • additional_headers - Additional headers to include in the request
  • additional_query_params - Additional query parameters to include

get_timeout

Convert timeout to httpx.Timeout if set.

fishaudio.core.iterators

Audio stream wrappers with collection utilities.

AudioStream Objects

Wrapper for sync audio byte streams with collection utilities. This class wraps an iterator of audio bytes and provides a convenient .collect() method to gather all chunks into a single bytes object. Examples:

__init__

Initialize the audio iterator wrapper. Arguments:
  • iterator - The underlying iterator of audio bytes
  • on_close - Called by close() to release the underlying resource, for example the open HTTP response
  • headers - Headers of the HTTP response that opened the stream

__iter__

Allow direct iteration over audio chunks.

close

Stop the stream and release the underlying connection. Safe to call more than once, and before iteration has started.

collect

Collect all audio chunks into a single bytes object. This consumes the iterator and returns all audio data as bytes. After calling this method, the iterator cannot be used again. Returns: Complete audio data as bytes Examples:

AsyncAudioStream Objects

Wrapper for async audio byte streams with collection utilities. This class wraps an async iterator of audio bytes and provides a convenient .collect() method to gather all chunks into a single bytes object. Examples:

__init__

Initialize the async audio iterator wrapper. Arguments:
  • async_iterator - The underlying async iterator of audio bytes
  • on_close - Awaited by aclose() to release the underlying resource, for example the open HTTP response
  • headers - Headers of the HTTP response that opened the stream

__aiter__

Allow direct async iteration over audio chunks.

aclose

Stop the stream and release the underlying connection. Safe to call more than once, and before iteration has started.

collect

Collect all audio chunks into a single bytes object. This consumes the async iterator and returns all audio data as bytes. After calling this method, the iterator cannot be used again. Returns: Complete audio data as bytes Examples:

_Timeline Objects

Keeps the newest timing snapshot of every text chunk.

duration

End of the last text chunk, or None when the API did not report it. The API reports audio length only inside timing snapshots. Without a snapshot for the last chunk, the end of the audio is unknown: earlier chunks would give a length that is too short, and no chunk gives none.

TTSTimestampStream Objects

Sync stream of text-to-speech audio with timestamps. Iterating yields TTSTimestampEvent objects as the server produces them. While you iterate, segments holds the timings received so far, measured from the start of the complete audio. Alternatively, call collect() instead of iterating to get the complete audio with its final timings. Examples:

__init__

Initialize the stream. Arguments:
  • iterator - The underlying iterator of events
  • on_close - Called by close() to release the underlying resource, for example the open HTTP response
  • headers - Headers of the HTTP response that opened the stream

segments

Timings received so far, in speaking order. Times are in seconds from the start of the complete audio. Entries near the end can still be corrected by later events, so read this again after each event instead of appending to an earlier copy. Empty until the first timings arrive, and it stays empty when the API has no timings for the text (for example text without words). The audio still arrives in full.

close

Stop the stream and release the underlying connection. Safe to call more than once, and before iteration has started.

collect

Read the whole stream and return the complete audio with its timings. Call this instead of iterating, not after it. Events that were already yielded are not kept, so the complete audio can no longer be returned once iteration has started; in that case use the audio you received and read segments when the stream ends. Returns: TTSTimestampResult with the complete audio and final timings. When the API has no timings for the text, segments is empty and duration is None; the audio is still complete. Raises:
  • RuntimeError - If iteration has already started

AsyncTTSTimestampStream Objects

Async stream of text-to-speech audio with timestamps. Iterating yields TTSTimestampEvent objects as the server produces them. While you iterate, segments holds the timings received so far, measured from the start of the complete audio. Alternatively, call collect() instead of iterating to get the complete audio with its final timings. Examples:

__init__

Initialize the stream. Arguments:
  • async_iterator - The underlying async iterator of events
  • on_close - Awaited by aclose() to release the underlying resource, for example the open HTTP response
  • headers - Headers of the HTTP response that opened the stream

segments

Timings received so far, in speaking order. Times are in seconds from the start of the complete audio. Entries near the end can still be corrected by later events, so read this again after each event instead of appending to an earlier copy. Empty until the first timings arrive, and it stays empty when the API has no timings for the text (for example text without words). The audio still arrives in full.

aclose

Stop the stream and release the underlying connection. Safe to call more than once, and before iteration has started.

collect

Read the whole stream and return the complete audio with its timings. Call this instead of iterating, not after it. Events that were already yielded are not kept, so the complete audio can no longer be returned once iteration has started; in that case use the audio you received and read segments when the stream ends. Returns: TTSTimestampResult with the complete audio and final timings. When the API has no timings for the text, segments is empty and duration is None; the audio is still complete. Raises:
  • RuntimeError - If iteration has already started

fishaudio.core._ws_utils

Internal helpers for synchronous httpx-ws sessions.

interrupt_writes

Make a socket write that is blocked in another thread fail now. A write blocks for as long as the peer does not read, and httpx-ws holds its write lock meanwhile, so nothing else can be sent either, not even the close frame. Shutting the socket down is the only way to end that from outside.

drain_reader

Send the close frame, shut the socket down, and wait for httpx-ws’s reader thread to exit before the session’s own close() frees the fd. Why this is needed (Linux only in practice): httpx-ws’s sync WebSocketSession reads on a background thread and closes the socket from the calling thread. A read that has not started yet is harmless: CPython’s SSLSocket._real_close sets _sslobj = None before closing the fd, so a later read falls through to socket.recv on fd -1 and fails with EBADF. The problem is the read that is already in flight. On Linux, close() does not interrupt a thread blocked in recv(). OpenSSL (with read_ahead off) fetches a TLS record header and body with separate read(fd) calls on the fd number cached in its BIO, so when the server’s close-frame reply arrives the second read() can land on a brand-new connection that has since reused the same fd number, and that new session fails with [SSL: WRONG_VERSION_NUMBER] or a similar TLS error. macOS wakes the blocked reader with EBADF on close(), so it is unaffected. The fix is to end the in-flight read before the fd is freed: send the close frame (so the server still sees a clean 1000 close rather than 1006; a peer that has stopped reading does not get one, see below), then shutdown(SHUT_RDWR) the socket, which wakes the blocked reader with EOF, and join the reader thread. The later close() sees LOCAL_CLOSING and skips sending a second frame. Residual risk: if httpx-ws has already closed the socket on one of its own error paths (keepalive ping timeout, or a sender WriteError triggering close()), the fd is already freed, shutdown() fails with EBADF, and the in-flight read can still race. That can only be fixed inside httpx-ws’s close().