Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,44 @@ audio = client.tts.convert(
| `client.voices` | Voice management | `list()`, `get()`, `create()`, `update()`, `delete()` |
| `client.account` | Account info | `get_credits()`, `get_package()` |

## Tracing

To continue your trace in the Fish Audio API, send a W3C `traceparent` header on each request. Use one of the ways below. A `traceparent` that the OpenTelemetry instrumentation sends replaces one you set yourself.

**With OpenTelemetry**, configure a tracer provider and enable [`opentelemetry-instrumentation-httpx`](https://pypi.org/project/opentelemetry-instrumentation-httpx/). HTTP calls and the WebSocket handshakes of `tts.stream_websocket()` and `asr.stream_websocket()` then carry the current trace: the same trace id, under a client span that the instrumentation creates. A WebSocket stream connects when you first iterate it, so iterate it inside your span.

```python
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor

HTTPXClientInstrumentor().instrument()
```

**Without OpenTelemetry**, pass the header with each call:

```python
from fishaudio.core import RequestOptions, WebSocketOptions

headers = {"traceparent": traceparent}
audio = client.tts.convert(text="Hello!", request_options=RequestOptions(additional_headers=headers))
stream = client.tts.stream_websocket(text_chunks(), ws_options=WebSocketOptions(additional_headers=headers))
```

Or give the client an `httpx_client` with a request event hook, which runs for HTTP calls and WebSocket handshakes alike (with `AsyncFishAudio`, use an `httpx.AsyncClient` and an async hook). A client you pass in keeps its own settings, so set its `timeout`: httpx's default is 5 seconds.

```python
import httpx

def add_traceparent(request):
request.headers["traceparent"] = current_traceparent()

http_client = httpx.Client(
base_url="https://api.fish.audio",
timeout=240.0,
event_hooks={"request": [add_traceparent]},
)
client = FishAudio(httpx_client=http_client)
```

## Error Handling

```python
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ asyncio_mode = "auto"
[dependency-groups]
dev = [
"fish-audio-sdk[utils]",
"opentelemetry-instrumentation-httpx>=0.62b1",
"opentelemetry-sdk>=1.41.1",
"poethepoet>=0.32.0",
"pydoc-markdown>=4.8.2",
"pytest>=8.3.5",
Expand Down
39 changes: 35 additions & 4 deletions src/fishaudio/core/client_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
)

from .request_options import RequestOptions
from .websocket_options import WebSocketOptions


def _api_error(status: int, message: str, body: Optional[str] = None) -> APIError:
Expand Down Expand Up @@ -190,7 +191,8 @@ def get_headers(
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.
to the SDK's own. ``Authorization`` and ``User-Agent`` are each sent
once: given in two spellings, the last one given is used.
"""
headers: dict[str, str] = {"Authorization": f"Bearer {self.api_key}"}
# Read from the client on every call, so a User-Agent changed on a
Expand All @@ -199,10 +201,16 @@ def get_headers(
caller = _caller_user_agent(getattr(self, "_client", None))
extra = {}
for name, value in (additional_headers or {}).items():
if name.lower() == "user-agent":
lowered = name.lower()
if lowered == "user-agent":
caller = value
else:
extra[name] = value
continue
if lowered == "authorization":
# Sent once: with two spellings, the last one given wins,
# as for User-Agent.
for given in [k for k in extra if k.lower() == lowered]:
del extra[given]
extra[name] = value
replaced = {name.lower() for name in extra}
headers = {k: v for k, v in headers.items() if k.lower() not in replaced}
headers.update(extra)
Expand Down Expand Up @@ -238,6 +246,29 @@ def _prepare_request_kwargs(
kwargs["params"] = params


def _handshake_headers(
client_wrapper: BaseClientWrapper,
model: str,
ws_options: Optional[WebSocketOptions],
) -> httpx.Headers:
"""Build the headers of a WebSocket handshake, as for an HTTP call.

``ws_options.additional_headers`` go through ``get_headers()``: an
``Authorization`` there replaces the API key and a ``User-Agent`` is
appended to the SDK's own, in any casing. ``model`` is the method's
argument, whatever the additional headers say.
"""
additional = {
name: value
for name, value in (
(ws_options.additional_headers if ws_options else None) or {}
).items()
if name.lower() != "model"
}
additional["model"] = model
return httpx.Headers(client_wrapper.get_headers(additional))


class ClientWrapper(BaseClientWrapper):
"""Wrapper for httpx.Client that handles authentication and error handling."""

Expand Down
16 changes: 13 additions & 3 deletions src/fishaudio/core/websocket_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ class WebSocketOptions:
"""
Options for configuring WebSocket connections.

These options 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/
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
Expand All @@ -22,9 +23,16 @@ class WebSocketOptions:
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.

Note:
Parameter descriptions adapted from httpx_ws documentation.
Descriptions of the httpx_ws options adapted from httpx_ws documentation.
"""

def __init__(
Expand All @@ -34,11 +42,13 @@ def __init__(
keepalive_ping_interval_seconds: Optional[float] = None,
max_message_size_bytes: Optional[int] = None,
queue_size: Optional[int] = None,
additional_headers: Optional[dict[str, str]] = None,
):
self.keepalive_ping_timeout_seconds = keepalive_ping_timeout_seconds
self.keepalive_ping_interval_seconds = keepalive_ping_interval_seconds
self.max_message_size_bytes = max_message_size_bytes
self.queue_size = queue_size
self.additional_headers = additional_headers

def to_httpx_ws_kwargs(self) -> dict[str, Any]:
"""Convert to kwargs dict for httpx_ws aconnect_ws/connect_ws."""
Expand Down
5 changes: 3 additions & 2 deletions src/fishaudio/resources/asr.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
RequestOptions,
WebSocketOptions,
)
from fishaudio.core.client_wrapper import _handshake_headers
from fishaudio.types import (
ASRContext,
ASRRealtimeConfig,
Expand Down Expand Up @@ -255,7 +256,7 @@ def audio_chunks():
```
"""
ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {}
headers = self._client.get_headers({"model": model})
headers = _handshake_headers(self._client, model, ws_options)
client = self._client.client

return ASRRealtimeStream(
Expand Down Expand Up @@ -452,7 +453,7 @@ async def audio_chunks():
```
"""
ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {}
headers = self._client.get_headers({"model": model})
headers = _handshake_headers(self._client, model, ws_options)
client = self._client.client

return AsyncASRRealtimeStream(
Expand Down
7 changes: 5 additions & 2 deletions src/fishaudio/resources/tts.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
)
from fishaudio.core._sse import ServerSentEvent, SSEDecoder
from fishaudio.core._ws_utils import drain_reader
from fishaudio.core.client_wrapper import _handshake_headers
from fishaudio.core.iterators import (
AsyncAudioStream,
AsyncTTSTimestampStream,
Expand Down Expand Up @@ -588,6 +589,7 @@ def text_generator():

# Prepare WebSocket connection kwargs
ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {}
headers = _handshake_headers(self._client, model, ws_options)

executor = ThreadPoolExecutor(max_workers=max_workers)

Expand All @@ -596,7 +598,7 @@ def text_generator():
with connect_ws(
"/v1/tts/live",
client=self._client.client,
headers=self._client.get_headers({"model": model}),
headers=headers,
**ws_kwargs,
) as ws:

Expand Down Expand Up @@ -1066,12 +1068,13 @@ async def text_generator():

# Prepare WebSocket connection kwargs
ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {}
headers = _handshake_headers(self._client, model, ws_options)

ws: AsyncWebSocketSession
async with aconnect_ws(
"/v1/tts/live",
client=self._client.client,
headers=self._client.get_headers({"model": model}),
headers=headers,
**ws_kwargs,
) as ws:

Expand Down
88 changes: 85 additions & 3 deletions tests/unit/realtime_server.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
"""A scripted WebSocket server that speaks the server side of /v1/asr/realtime.
"""A scripted WebSocket server for the SDK's realtime endpoints.

It listens on a real TCP socket and frames messages with wsproto, so the tests
exercise the SDK's actual transport (httpx + httpx-ws) rather than mocks of it.
"""

from __future__ import annotations

import asyncio
import contextlib
import socket
import threading
import time
from collections import deque
from typing import Any, Callable, Optional
from typing import TYPE_CHECKING, Any, Callable, Optional

import ormsgpack
from wsproto import ConnectionType, WSConnection
Expand All @@ -24,6 +25,11 @@
Request,
)

from fishaudio import AsyncFishAudio, FishAudio

if TYPE_CHECKING:
from fishaudio.core import WebSocketOptions

SESSION_STARTED = {
"type": "session_started",
"seq": 0,
Expand Down Expand Up @@ -52,6 +58,10 @@ def __init__(self, sock: socket.socket, reject_status: Optional[int]):
self._pending: deque[dict[str, Any]] = deque()
self._partial = b""
self.headers: dict[str, str] = {}
# The handshake's headers in order, as wsproto reports them: names in
# lower case, repeated names kept, without Host and the WebSocket
# negotiation headers it handles itself.
self.header_list: list[tuple[str, str]] = []
self.path: Optional[str] = None
self.received: list[dict[str, Any]] = []
self.close_code: Optional[int] = None
Expand All @@ -72,7 +82,10 @@ def _read(self) -> None:
for event in self._ws.events():
if isinstance(event, Request):
self.path = event.target
self.headers = {k.decode(): v.decode() for k, v in event.extra_headers}
self.header_list = [
(k.decode(), v.decode()) for k, v in event.extra_headers
]
self.headers = dict(self.header_list)
if self._reject_status is not None:
self._write(RejectConnection(status_code=self._reject_status))
raise ClientGone
Expand Down Expand Up @@ -205,3 +218,72 @@ def stop(self) -> Connection:
def close(self) -> None:
"""Stop listening. Called by stop(); safe to call again."""
self._listener.close()


# Driving each of the SDK's four WebSocket paths against a RealtimeServer.

WS_PATHS = ["tts", "asr", "async tts", "async asr"]


def _tts_script(conn: Connection) -> None:
conn.send({"event": "finish", "reason": "stop"})


def _asr_script(conn: Connection) -> None:
conn.recv()
conn.send(SESSION_STARTED)
conn.send({"type": "session_done", "seq": 1, "stats": {"audio_ms": 0, "turns": 0}})
conn.close(1000)


def _default_client(url: str, is_async: bool) -> Any:
if is_async:
return AsyncFishAudio(api_key="test-key", base_url=url)
return FishAudio(api_key="test-key", base_url=url)


@contextlib.contextmanager
def ws_server(path: str, make_client: Callable[[str, bool], Any] = _default_client):
"""Yield (server, client) for one connection on ``path`` (one of WS_PATHS)."""
server = RealtimeServer(_asr_script if path.endswith("asr") else _tts_script)
is_async = path.startswith("async")
client = make_client(server.url, is_async)
try:
yield server, client
finally:
if is_async:
asyncio.run(client.close())
else:
client.close()
server.close()


async def _aiter(items: list[Any]) -> Any:
for item in items:
yield item


def open_stream(
client: Any, path: str, ws_options: Optional[WebSocketOptions] = None
) -> Any:
"""A stream on ``path``. It connects when ``consume`` iterates it."""
if path.endswith("asr"):
resource, items = client.asr, [b"\x00\x00" * 320]
else:
resource, items = client.tts, ["Hello"]
source = _aiter(items) if path.startswith("async") else iter(items)
return resource.stream_websocket(source, ws_options=ws_options)


def consume(stream: Any) -> None:
"""Iterate a sync or async stream to its end."""
if hasattr(stream, "__anext__"):

async def drain() -> None:
async for _ in stream:
pass

asyncio.run(drain())
else:
for _ in stream:
pass
Loading