From 40eb257c9cdac1244041702ff1066c6d382d6822 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:51:09 -0800 Subject: [PATCH 1/9] feat(websocket): accept additional handshake headers in WebSocketOptions WebSocketOptions.additional_headers adds headers to the handshake of tts.stream_websocket and asr.stream_websocket, sync and async, so a caller without OpenTelemetry can send a traceparent on a single WebSocket call as RequestOptions already allows on HTTP. The SDK's own Authorization, User-Agent and model headers are kept whatever the casing of a name given. The README gains a Tracing section: opentelemetry-instrumentation-httpx covers HTTP and both handshakes; without it, use the per-call options or an httpx_client with a request event hook. --- README.md | 33 ++++ pyproject.toml | 2 + src/fishaudio/core/websocket_options.py | 13 +- src/fishaudio/resources/asr.py | 9 +- src/fishaudio/resources/tts.py | 11 +- tests/unit/realtime_server.py | 86 ++++++++- tests/unit/test_tracing.py | 160 +++++++++++++++++ tests/unit/test_websocket_headers.py | 61 +++++++ uv.lock | 230 +++++++++++++++++++++++- 9 files changed, 594 insertions(+), 11 deletions(-) create mode 100644 tests/unit/test_tracing.py create mode 100644 tests/unit/test_websocket_headers.py diff --git a/README.md b/README.md index f1ca832..9d1403f 100644 --- a/README.md +++ b/README.md @@ -303,6 +303,39 @@ 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; if the OpenTelemetry instrumentation is enabled, it replaces a `traceparent` you set yourself. + +**With OpenTelemetry**, 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): + +```python +import httpx + +def add_traceparent(request): + request.headers["traceparent"] = current_traceparent() + +client = FishAudio(httpx_client=httpx.Client(base_url="https://api.fish.audio", event_hooks={"request": [add_traceparent]})) +``` + ## Error Handling ```python diff --git a/pyproject.toml b/pyproject.toml index bb44d0c..fe7f86e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", diff --git a/src/fishaudio/core/websocket_options.py b/src/fishaudio/core/websocket_options.py index 4e9132a..a1556d8 100644 --- a/src/fishaudio/core/websocket_options.py +++ b/src/fishaudio/core/websocket_options.py @@ -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 @@ -22,9 +23,13 @@ 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": ...}``. The headers the SDK sets itself + (``Authorization``, ``User-Agent``, ``model``) are kept, whatever the + casing of a name given here. 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__( @@ -34,11 +39,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.""" diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 514c5ac..81f73d7 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -3,6 +3,7 @@ from collections.abc import AsyncIterable, Iterable from typing import Optional, Union +import httpx import ormsgpack from httpx_ws import aconnect_ws, connect_ws @@ -226,7 +227,9 @@ def audio_chunks(): ``` """ ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - headers = self._client.get_headers({"model": model}) + # The SDK's own headers replace any spelling of the same name. + headers = httpx.Headers(ws_options.additional_headers if ws_options else None) + headers.update(self._client.get_headers({"model": model})) client = self._client.client return ASRRealtimeStream( @@ -413,7 +416,9 @@ async def audio_chunks(): ``` """ ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - headers = self._client.get_headers({"model": model}) + # The SDK's own headers replace any spelling of the same name. + headers = httpx.Headers(ws_options.additional_headers if ws_options else None) + headers.update(self._client.get_headers({"model": model})) client = self._client.client return AsyncASRRealtimeStream( diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 73d83f2..fe9fb56 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -8,6 +8,7 @@ from concurrent.futures import ThreadPoolExecutor from typing import Optional, Union +import httpx import ormsgpack from httpx_ws import AsyncWebSocketSession, WebSocketSession, aconnect_ws, connect_ws @@ -555,6 +556,9 @@ def text_generator(): # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} + # The SDK's own headers replace any spelling of the same name. + headers = httpx.Headers(ws_options.additional_headers if ws_options else None) + headers.update(self._client.get_headers({"model": model})) executor = ThreadPoolExecutor(max_workers=max_workers) @@ -563,7 +567,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: @@ -1020,12 +1024,15 @@ async def text_generator(): # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} + # The SDK's own headers replace any spelling of the same name. + headers = httpx.Headers(ws_options.additional_headers if ws_options else None) + headers.update(self._client.get_headers({"model": model})) 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: diff --git a/tests/unit/realtime_server.py b/tests/unit/realtime_server.py index 550e573..d6d76ce 100644 --- a/tests/unit/realtime_server.py +++ b/tests/unit/realtime_server.py @@ -1,4 +1,4 @@ -"""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. @@ -6,12 +6,13 @@ 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 @@ -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, @@ -48,6 +54,8 @@ 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] = {} + # Every handshake header line in order, repeated names included. + self.header_list: list[tuple[str, str]] = [] self.path: Optional[str] = None self.received: list[dict[str, Any]] = [] self.close_code: Optional[int] = None @@ -68,7 +76,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 @@ -201,3 +212,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 diff --git a/tests/unit/test_tracing.py b/tests/unit/test_tracing.py new file mode 100644 index 0000000..0dc8549 --- /dev/null +++ b/tests/unit/test_tracing.py @@ -0,0 +1,160 @@ +"""What the README's Tracing section promises, checked through the real transport. + +With opentelemetry-instrumentation-httpx enabled, every HTTP call and WebSocket +handshake carries the active trace. Without it, a custom httpx client with a +request event hook reaches the same requests. +""" + +import asyncio +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import httpx +import pytest +from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor +from opentelemetry.sdk.trace import TracerProvider + +from fishaudio import AsyncFishAudio, FishAudio + +from .realtime_server import WS_PATHS, consume, open_stream, ws_server + +ASR_RESPONSE = {"text": "Hello", "duration": 1.0, "segments": []} + + +class _Handler(BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers["content-length"])) + self.server.requests.append(self.headers.items()) + body = json.dumps(ASR_RESPONSE).encode() if self.path == "/v1/asr" else b"ID3" + self.send_response(200) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +@pytest.fixture +def http_server(): + """A local HTTP server that records each request's header lines.""" + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + server.requests = [] + server.url = f"http://127.0.0.1:{server.server_address[1]}" + threading.Thread(target=server.serve_forever, daemon=True).start() + yield server + server.shutdown() + server.server_close() + + +def call_http(client, name): + """Make one HTTP call: tts.convert or asr.transcribe, sync or async.""" + if name.endswith("tts.convert"): + call = client.tts.convert(text="Hello") + else: + call = client.asr.transcribe(audio=b"\x00") + if name.startswith("async"): + + async def run(): + await call + await client.close() + + asyncio.run(run()) + else: + client.close() + + +HTTP_CALLS = [ + "tts.convert", + "asr.transcribe", + "async tts.convert", + "async asr.transcribe", +] + + +def sdk_client(url, is_async): + if is_async: + return AsyncFishAudio(api_key="test-key", base_url=url) + return FishAudio(api_key="test-key", base_url=url) + + +def values(header_list, name): + return [value for key, value in header_list if key.lower() == name] + + +def trace_id(traceparent): + return int(traceparent.split("-")[1], 16) + + +@pytest.fixture +def tracer(): + provider = TracerProvider() + HTTPXClientInstrumentor().instrument(tracer_provider=provider) + yield provider.get_tracer("app") + HTTPXClientInstrumentor().uninstrument() + + +@pytest.mark.parametrize("name", HTTP_CALLS) +def test_instrumented_http_call_carries_the_active_trace(tracer, http_server, name): + client = sdk_client(http_server.url, name.startswith("async")) + with tracer.start_as_current_span("request") as span: + call_http(client, name) + + [traceparent] = values(http_server.requests[0], "traceparent") + assert trace_id(traceparent) == span.get_span_context().trace_id + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_instrumented_handshake_carries_the_active_trace(tracer, path): + with ws_server(path) as (server, client), tracer.start_as_current_span("x") as span: + consume(open_stream(client, path)) + + [traceparent] = values(server.stop().header_list, "traceparent") + assert trace_id(traceparent) == span.get_span_context().trace_id + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_stream_iterated_after_the_span_ends_is_not_in_its_trace(tracer, path): + with ws_server(path) as (server, client): + with tracer.start_as_current_span("request") as span: + stream = open_stream(client, path) + consume(stream) + + # The connection opens on the first iteration, so the instrumentation + # starts a new trace there. + [traceparent] = values(server.stop().header_list, "traceparent") + assert trace_id(traceparent) != span.get_span_context().trace_id + + +def _hooked_client(url, is_async): + """The README's alternative: a client whose request hook adds a header.""" + if is_async: + + async def ahook(request): + request.headers["traceparent"] = "from-hook" + + http = httpx.AsyncClient(base_url=url, event_hooks={"request": [ahook]}) + return AsyncFishAudio(api_key="test-key", httpx_client=http) + + def hook(request): + request.headers["traceparent"] = "from-hook" + + http = httpx.Client(base_url=url, event_hooks={"request": [hook]}) + return FishAudio(api_key="test-key", httpx_client=http) + + +@pytest.mark.parametrize("name", HTTP_CALLS) +def test_request_hook_reaches_http_calls(http_server, name): + call_http(_hooked_client(http_server.url, name.startswith("async")), name) + + assert values(http_server.requests[0], "traceparent") == ["from-hook"] + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_request_hook_reaches_handshakes(path): + with ws_server(path, _hooked_client) as (server, client): + consume(open_stream(client, path)) + + assert values(server.stop().header_list, "traceparent") == ["from-hook"] diff --git a/tests/unit/test_websocket_headers.py b/tests/unit/test_websocket_headers.py new file mode 100644 index 0000000..2a7cd6e --- /dev/null +++ b/tests/unit/test_websocket_headers.py @@ -0,0 +1,61 @@ +"""WebSocketOptions.additional_headers, checked on the handshake each path sends.""" + +import pytest + +from fishaudio.core import WebSocketOptions + +from .realtime_server import WS_PATHS, consume, open_stream, ws_server + +TRACEPARENT = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" + + +def handshake(path, ws_options=None): + """The handshake's header lines, in order, as the server read them.""" + with ws_server(path) as (server, client): + consume(open_stream(client, path, ws_options)) + return server.stop().header_list + + +def values(header_list, name): + return [value for key, value in header_list if key == name] + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_additional_headers_are_sent_on_the_handshake(path): + extra = {"traceparent": TRACEPARENT, "X-Request-Source": "test"} + + sent = handshake(path, WebSocketOptions(additional_headers=extra)) + + assert values(sent, "traceparent") == [TRACEPARENT] + assert values(sent, "x-request-source") == ["test"] + assert extra == {"traceparent": TRACEPARENT, "X-Request-Source": "test"} + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_sdk_headers_win_over_additional_headers_in_any_casing(path): + default = handshake(path) + + sent = handshake( + path, + WebSocketOptions( + additional_headers={ + "AUTHORIZATION": "Bearer other", + "Model": "other", + "user-agent": "other", + } + ), + ) + + for name in ("authorization", "model", "user-agent"): + assert values(sent, name) == values(default, name) + assert values(sent, "authorization") == ["Bearer test-key"] + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_default_options_send_the_same_header_names(path): + without_options = handshake(path) + with_default_options = handshake(path, WebSocketOptions()) + + names = [name for name, _ in without_options] + assert [name for name, _ in with_default_options] == names + assert {"authorization", "user-agent", "model"} <= set(names) diff --git a/uv.lock b/uv.lock index b4753f0..3ce1eed 100644 --- a/uv.lock +++ b/uv.lock @@ -652,7 +652,7 @@ wheels = [ [[package]] name = "fish-audio-sdk" -version = "1.5.0" +version = "1.6.0" source = { editable = "." } dependencies = [ { name = "httpx" }, @@ -673,6 +673,10 @@ utils = [ [package.dev-dependencies] dev = [ { name = "fish-audio-sdk", extra = ["utils"] }, + { name = "opentelemetry-instrumentation-httpx", version = "0.62b1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" }, + { name = "opentelemetry-instrumentation-httpx", version = "0.66b2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" }, + { name = "opentelemetry-sdk", version = "1.41.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" }, + { name = "opentelemetry-sdk", version = "1.45.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" }, { name = "poethepoet", version = "0.37.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" }, { name = "poethepoet", version = "0.41.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" }, { name = "pydoc-markdown" }, @@ -701,6 +705,8 @@ provides-extras = ["utils"] [package.metadata.requires-dev] dev = [ { name = "fish-audio-sdk", extras = ["utils"], editable = "." }, + { name = "opentelemetry-instrumentation-httpx", specifier = ">=0.62b1" }, + { name = "opentelemetry-sdk", specifier = ">=1.41.1" }, { name = "poethepoet", specifier = ">=0.32.0" }, { name = "pydoc-markdown", specifier = ">=4.8.2" }, { name = "pytest", specifier = ">=8.3.5" }, @@ -795,6 +801,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/23/408243171aa9aaba178d3e2559159c24c1171a641aa83b67bdd3394ead8e/idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8", size = 72340, upload-time = "2026-05-12T22:45:55.733Z" }, ] +[[package]] +name = "importlib-metadata" +version = "8.7.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "zipp" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f3/49/3b30cad09e7771a4982d9975a8cbf64f00d4a1ececb53297f1d9a7be1b10/importlib_metadata-8.7.1.tar.gz", hash = "sha256:49fef1ae6440c182052f407c8d34a68f72efc36db9ca90dc0113398f2fdde8bb", size = 57107, upload-time = "2025-12-21T10:00:19.278Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/5e/f8e9a1d23b9c20a551a8a02ea3637b4642e22c2626e3a13a9a29cdea99eb/importlib_metadata-8.7.1-py3-none-any.whl", hash = "sha256:5a1f80bf1daa489495071efbb095d75a634cf28a8bc299581244063b53176151", size = 27865, upload-time = "2025-12-21T10:00:18.329Z" }, +] + [[package]] name = "iniconfig" version = "2.1.0" @@ -1172,6 +1190,207 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/95/8e/2844c3959ce9a63acc7c8e50881133d86666f0420bcde695e115ced0920f/numpy-2.3.4-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:81b3a59793523e552c4a96109dde028aa4448ae06ccac5a76ff6532a85558a7f", size = 12973130, upload-time = "2025-10-15T16:18:09.397Z" }, ] +[[package]] +name = "opentelemetry-api" +version = "1.41.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "importlib-metadata" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/fa/fc/b7564cbef36601aef0d6c9bc01f7badb64be8e862c2e1c3c5c3b43b53e4f/opentelemetry_api-1.41.1.tar.gz", hash = "sha256:0ad1814d73b875f84494387dae86ce0b12c68556331ce6ce8fe789197c949621", size = 71416, upload-time = "2026-04-24T13:15:38.262Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/29/59/3e7118ed140f76b0982ba4321bdaed1997a0473f9720de2d10788a577033/opentelemetry_api-1.41.1-py3-none-any.whl", hash = "sha256:a22df900e75c76dc08440710e51f52f1aa6b451b429298896023e60db5b3139f", size = 69007, upload-time = "2026-04-24T13:15:15.662Z" }, +] + +[[package]] +name = "opentelemetry-api" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation" +version = "0.62b1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.41.1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "packaging" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/52/cb/0523b92c112a6cc70be43724343dc45225d3af134419844d7879a07755d4/opentelemetry_instrumentation-0.62b1.tar.gz", hash = "sha256:90e92a905ba4f84db06ac3aec96701df6c079b2d66e9379f8739f0a1bdcc7f45", size = 34043, upload-time = "2026-04-24T13:22:31.997Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/0f/45adbaea1f81b847cffdcee4f4b5f89297e42facf7fac78c7aaac4c38e75/opentelemetry_instrumentation-0.62b1-py3-none-any.whl", hash = "sha256:976fc6e640f2006599e97429c949e622c108d0c17c2059347d1e6c93c707f257", size = 34163, upload-time = "2026-04-24T13:21:31.722Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.45.2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "packaging" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/b9/46a136199fa6928eecefec8418867a460d94f01c608a85d22bd2ed4e8d48/opentelemetry_instrumentation-0.66b2.tar.gz", hash = "sha256:02b094150e53b76f5906d75e628dbb3833bbc6e62fa109b5c7ba0c081865e923", size = 43305, upload-time = "2026-10-29T17:38:11.618Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation-httpx" +version = "0.62b1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.41.1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-instrumentation", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-util-http", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/33/cb/7a418e69c7dad281803529cb4f6de1b747d802cca44c38032668690b4836/opentelemetry_instrumentation_httpx-0.62b1.tar.gz", hash = "sha256:a1fac9bcc3a6ef5996a7990563f1af0798468b2c146de535fd598369383fba7e", size = 24181, upload-time = "2026-04-24T13:22:52.124Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/e0/eca824e9492ccec00e055bdd243aeda8eb7c5eda746d98af4d7a2d97ecf3/opentelemetry_instrumentation_httpx-0.62b1-py3-none-any.whl", hash = "sha256:88614015df451d61bc7e73f22524e6f223611f80b6caad2f6bdcbe05fa0df653", size = 17201, upload-time = "2026-04-24T13:21:58.072Z" }, +] + +[[package]] +name = "opentelemetry-instrumentation-httpx" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.45.2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-instrumentation", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-util-http", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/41/43/3204ca7e7d91bd9e1b569a98a5f9252c98ae70ba3bb562d2770c34e21d49/opentelemetry_instrumentation_httpx-0.66b2.tar.gz", hash = "sha256:b4c81e4a6dc7b8d7cb2d3088eb8848f6db6bd4abdc443ac9586ec176f1460187", size = 26638, upload-time = "2026-10-29T17:38:31.46Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/53/40/37d6161dcd95285c9c3eb75e2dbeb1dbc6e868551532735374918a22e298/opentelemetry_instrumentation_httpx-0.66b2-py3-none-any.whl", hash = "sha256:93e2b6ab1a505d76ec3d98abcf7e8527d4712167d6c3b5ebbb9c68d9309d9ba5", size = 17723, upload-time = "2026-10-29T17:37:33.735Z" }, +] + +[[package]] +name = "opentelemetry-sdk" +version = "1.41.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.41.1", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.62b1", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/d0/54ee30dab82fb0acda23d144502771ff76ef8728459c83c3e89ef9fb1825/opentelemetry_sdk-1.41.1.tar.gz", hash = "sha256:724b615e1215b5aeacda0abb8a6a8922c9a1853068948bd0bd225a56d0c792e6", size = 230180, upload-time = "2026-04-24T13:15:50.991Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b4/e7/a1420b698aad018e1cf60fdbaaccbe49021fb415e2a0d81c242f4c518f54/opentelemetry_sdk-1.41.1-py3-none-any.whl", hash = "sha256:edee379c126c1bce952b0c812b48fe8ff35b30df0eecf17e98afa4d598b7d85d", size = 180213, upload-time = "2026-04-24T13:15:33.767Z" }, +] + +[[package]] +name = "opentelemetry-sdk" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.45.2", source = { registry = "https://pypi.org/simple" } }, + { name = "opentelemetry-semantic-conventions", version = "0.66b2", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, +] + +[[package]] +name = "opentelemetry-semantic-conventions" +version = "0.62b1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.41.1", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/de/911ac9e309052aca1b20b2d5549d3db45d1011e1a610e552c6ccdd1b64f8/opentelemetry_semantic_conventions-0.62b1.tar.gz", hash = "sha256:c5cc6e04a7f8c7cdd30be2ed81499fa4e75bfbd52c9cb70d40af1f9cd3619802", size = 145750, upload-time = "2026-04-24T13:15:52.236Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/eb/a6/83dc2ab6fa397ee66fba04fe2e74bdf7be3b3870005359ceb7689103c058/opentelemetry_semantic_conventions-0.62b1-py3-none-any.whl", hash = "sha256:cf506938103d331fbb78eded0d9788095f7fd59016f2bda813c3324e5a74a93c", size = 231620, upload-time = "2026-04-24T13:15:35.454Z" }, +] + +[[package]] +name = "opentelemetry-semantic-conventions" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +dependencies = [ + { name = "opentelemetry-api", version = "1.45.2", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, +] + +[[package]] +name = "opentelemetry-util-http" +version = "0.62b1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.10'", +] +sdist = { url = "https://files.pythonhosted.org/packages/24/1b/aa71b63e18d30a8384036b9937f40f7618f8030a7aa213155fb54f6f2b47/opentelemetry_util_http-0.62b1.tar.gz", hash = "sha256:adf6facbb89aef8f8bc566e2f04624942ba08a7b678b3479a91051a8f4dc70a3", size = 11393, upload-time = "2026-04-24T13:23:12.994Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/85/a9d9d32161c1ced61346267db4c9702da54f81ec5dc88214bc65c23f4e9d/opentelemetry_util_http-0.62b1-py3-none-any.whl", hash = "sha256:c57e8a6c19fc422c288e6074e882f506f85030b69b7376182f74f9257b9261f0", size = 9295, upload-time = "2026-04-24T13:22:28.078Z" }, +] + +[[package]] +name = "opentelemetry-util-http" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", + "python_full_version == '3.10.*'", +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/57/33566966a7bced4d02fbc672f92029184e4a743f5b531e44b4c0dc4c999b/opentelemetry_util_http-0.66b2.tar.gz", hash = "sha256:7ba066ea609202e474679ddf1d0f753a1e6619bd206b36afaecba4bbb86e25d0", size = 11587, upload-time = "2026-10-29T17:38:56.043Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/8d/39885564eefa43f6181acfa3d698af2f6b5fe3e64c86dce3f1b955f6397f/opentelemetry_util_http-0.66b2-py3-none-any.whl", hash = "sha256:c4bb5d6744e60353bcaa3e325bc529a1515346b51cb4d9c8e5b730579337e06d", size = 8383, upload-time = "2026-10-29T17:38:07.462Z" }, +] + [[package]] name = "ormsgpack" version = "1.11.0" @@ -2132,3 +2351,12 @@ sdist = { url = "https://files.pythonhosted.org/packages/23/97/b6f296d1e9cc1ec25 wheels = [ { url = "https://files.pythonhosted.org/packages/37/81/6acd6601f61e31cfb8729d3da6d5df966f80f374b78eff83760714487338/yapf-0.43.0-py3-none-any.whl", hash = "sha256:224faffbc39c428cb095818cf6ef5511fdab6f7430a10783fdfb292ccf2852ca", size = 256158, upload-time = "2024-11-14T00:11:39.37Z" }, ] + +[[package]] +name = "zipp" +version = "3.23.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/30/21/093488dfc7cc8964ded15ab726fad40f25fd3d788fd741cc1c5a17d78ee8/zipp-3.23.1.tar.gz", hash = "sha256:32120e378d32cd9714ad503c1d024619063ec28aad2248dc6672ad13edfa5110", size = 25965, upload-time = "2026-04-13T23:21:46.6Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/08/8a/0861bec20485572fbddf3dfba2910e38fe249796cb73ecdeb74e07eeb8d3/zipp-3.23.1-py3-none-any.whl", hash = "sha256:0b3596c50a5c700c9cb40ba8d86d9f2cc4807e9bedb06bcdf7fac85633e444dc", size = 10378, upload-time = "2026-04-13T23:21:45.386Z" }, +] From c7d5d8e70933b2ae0d75060a3f669d775d085f8f Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:25:13 -0800 Subject: [PATCH 2/9] fix(websocket): append a User-Agent in additional_headers to the SDK's own A User-Agent given in WebSocketOptions.additional_headers was replaced by the SDK's. It is now appended, as on HTTP calls, on all four handshakes. --- src/fishaudio/core/client_wrapper.py | 20 ++++++++++++++++++++ src/fishaudio/core/websocket_options.py | 5 +++-- src/fishaudio/resources/asr.py | 10 +++------- src/fishaudio/resources/tts.py | 10 +++------- tests/unit/test_websocket_headers.py | 20 ++++++++++++++------ 5 files changed, 43 insertions(+), 22 deletions(-) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index c95784e..a3c513a 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -20,6 +20,7 @@ ) from .request_options import RequestOptions +from .websocket_options import WebSocketOptions def _api_error(status: int, message: str, body: Optional[str] = None) -> APIError: @@ -209,6 +210,25 @@ 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. + + ``ws_options.additional_headers`` come first; the SDK's own headers replace + any spelling of the same name. The exception is ``User-Agent``, which is + appended to the SDK's own, as on HTTP calls. + """ + headers = httpx.Headers(ws_options.additional_headers if ws_options else None) + own = {"model": model} + if "user-agent" in headers: + own["User-Agent"] = headers["user-agent"] + headers.update(client_wrapper.get_headers(own)) + return headers + + class ClientWrapper(BaseClientWrapper): """Wrapper for httpx.Client that handles authentication and error handling.""" diff --git a/src/fishaudio/core/websocket_options.py b/src/fishaudio/core/websocket_options.py index a1556d8..595f828 100644 --- a/src/fishaudio/core/websocket_options.py +++ b/src/fishaudio/core/websocket_options.py @@ -25,8 +25,9 @@ class WebSocketOptions: from the server until the queue has room available. Default: 512. additional_headers: Extra headers to send on the WebSocket handshake, for example ``{"traceparent": ...}``. The headers the SDK sets itself - (``Authorization``, ``User-Agent``, ``model``) are kept, whatever the - casing of a name given here. The dict is not modified. + (``Authorization``, ``model``) are kept, whatever the casing of a + name given here; a ``User-Agent`` given here is appended to the + SDK's own. The dict is not modified. Note: Descriptions of the httpx_ws options adapted from httpx_ws documentation. diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 81f73d7..686c665 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -3,7 +3,6 @@ from collections.abc import AsyncIterable, Iterable from typing import Optional, Union -import httpx import ormsgpack from httpx_ws import aconnect_ws, connect_ws @@ -14,6 +13,7 @@ RequestOptions, WebSocketOptions, ) +from fishaudio.core.client_wrapper import handshake_headers from fishaudio.types import ( ASRContext, ASRRealtimeConfig, @@ -227,9 +227,7 @@ def audio_chunks(): ``` """ ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - # The SDK's own headers replace any spelling of the same name. - headers = httpx.Headers(ws_options.additional_headers if ws_options else None) - headers.update(self._client.get_headers({"model": model})) + headers = handshake_headers(self._client, model, ws_options) client = self._client.client return ASRRealtimeStream( @@ -416,9 +414,7 @@ async def audio_chunks(): ``` """ ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - # The SDK's own headers replace any spelling of the same name. - headers = httpx.Headers(ws_options.additional_headers if ws_options else None) - headers.update(self._client.get_headers({"model": model})) + headers = handshake_headers(self._client, model, ws_options) client = self._client.client return AsyncASRRealtimeStream( diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index fe9fb56..4cdc4af 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -8,7 +8,6 @@ from concurrent.futures import ThreadPoolExecutor from typing import Optional, Union -import httpx import ormsgpack from httpx_ws import AsyncWebSocketSession, WebSocketSession, aconnect_ws, connect_ws @@ -20,6 +19,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, @@ -556,9 +556,7 @@ def text_generator(): # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - # The SDK's own headers replace any spelling of the same name. - headers = httpx.Headers(ws_options.additional_headers if ws_options else None) - headers.update(self._client.get_headers({"model": model})) + headers = handshake_headers(self._client, model, ws_options) executor = ThreadPoolExecutor(max_workers=max_workers) @@ -1024,9 +1022,7 @@ async def text_generator(): # Prepare WebSocket connection kwargs ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - # The SDK's own headers replace any spelling of the same name. - headers = httpx.Headers(ws_options.additional_headers if ws_options else None) - headers.update(self._client.get_headers({"model": model})) + headers = handshake_headers(self._client, model, ws_options) ws: AsyncWebSocketSession async with aconnect_ws( diff --git a/tests/unit/test_websocket_headers.py b/tests/unit/test_websocket_headers.py index 2a7cd6e..274d945 100644 --- a/tests/unit/test_websocket_headers.py +++ b/tests/unit/test_websocket_headers.py @@ -3,6 +3,7 @@ import pytest from fishaudio.core import WebSocketOptions +from fishaudio.core.client_wrapper import USER_AGENT from .realtime_server import WS_PATHS, consume, open_stream, ws_server @@ -38,19 +39,26 @@ def test_sdk_headers_win_over_additional_headers_in_any_casing(path): sent = handshake( path, WebSocketOptions( - additional_headers={ - "AUTHORIZATION": "Bearer other", - "Model": "other", - "user-agent": "other", - } + additional_headers={"AUTHORIZATION": "Bearer other", "Model": "other"} ), ) - for name in ("authorization", "model", "user-agent"): + for name in ("authorization", "model"): assert values(sent, name) == values(default, name) assert values(sent, "authorization") == ["Bearer test-key"] +@pytest.mark.parametrize("path", WS_PATHS) +def test_a_user_agent_in_additional_headers_is_appended_to_the_sdks(path): + assert values(handshake(path), "user-agent") == [USER_AGENT] + + sent = handshake( + path, WebSocketOptions(additional_headers={"user-agent": "my-app/1.0"}) + ) + + assert values(sent, "user-agent") == [f"{USER_AGENT} my-app/1.0"] + + @pytest.mark.parametrize("path", WS_PATHS) def test_default_options_send_the_same_header_names(path): without_options = handshake(path) From d92c9586ff59e29e2863b55cb994503364a40dd2 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:31:32 -0800 Subject: [PATCH 3/9] test: pin that instrumentation replaces a traceparent set by hand --- tests/unit/test_tracing.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/unit/test_tracing.py b/tests/unit/test_tracing.py index 0dc8549..cb42c5f 100644 --- a/tests/unit/test_tracing.py +++ b/tests/unit/test_tracing.py @@ -16,6 +16,7 @@ from opentelemetry.sdk.trace import TracerProvider from fishaudio import AsyncFishAudio, FishAudio +from fishaudio.core import RequestOptions, WebSocketOptions from .realtime_server import WS_PATHS, consume, open_stream, ws_server @@ -158,3 +159,30 @@ def test_request_hook_reaches_handshakes(path): consume(open_stream(client, path)) assert values(server.stop().header_list, "traceparent") == ["from-hook"] + + +MANUAL = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_instrumentation_replaces_a_traceparent_set_by_hand_on_a_handshake( + tracer, path +): + options = WebSocketOptions(additional_headers={"traceparent": MANUAL}) + with ws_server(path) as (server, client), tracer.start_as_current_span("x") as span: + consume(open_stream(client, path, options)) + + [traceparent] = values(server.stop().header_list, "traceparent") + assert trace_id(traceparent) == span.get_span_context().trace_id + + +def test_instrumentation_replaces_a_traceparent_set_by_hand_on_an_http_call( + tracer, http_server +): + client = sdk_client(http_server.url, False) + options = RequestOptions(additional_headers={"traceparent": MANUAL}) + with tracer.start_as_current_span("request") as span: + client.tts.convert(text="hi", request_options=options) + + [traceparent] = values(http_server.requests[0], "traceparent") + assert trace_id(traceparent) == span.get_span_context().trace_id From 550c7986cc71a297f2c5847ae2b22bfa37f9bc5b Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:39:48 -0800 Subject: [PATCH 4/9] fix(websocket): with two spellings of User-Agent, append the last one, as on HTTP calls --- src/fishaudio/core/client_wrapper.py | 9 ++++++--- tests/unit/test_websocket_headers.py | 10 ++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index a3c513a..a8e1cff 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -221,10 +221,13 @@ def handshake_headers( any spelling of the same name. The exception is ``User-Agent``, which is appended to the SDK's own, as on HTTP calls. """ - headers = httpx.Headers(ws_options.additional_headers if ws_options else None) + additional = dict((ws_options.additional_headers if ws_options else None) or {}) own = {"model": model} - if "user-agent" in headers: - own["User-Agent"] = headers["user-agent"] + for name in list(additional): + if name.lower() == "user-agent": + # The last spelling wins, as in get_headers(). + own["User-Agent"] = additional.pop(name) + headers = httpx.Headers(additional) headers.update(client_wrapper.get_headers(own)) return headers diff --git a/tests/unit/test_websocket_headers.py b/tests/unit/test_websocket_headers.py index 274d945..3277c46 100644 --- a/tests/unit/test_websocket_headers.py +++ b/tests/unit/test_websocket_headers.py @@ -59,6 +59,16 @@ def test_a_user_agent_in_additional_headers_is_appended_to_the_sdks(path): assert values(sent, "user-agent") == [f"{USER_AGENT} my-app/1.0"] +@pytest.mark.parametrize("path", WS_PATHS) +def test_the_last_of_two_spellings_of_user_agent_is_the_one_appended(path): + extra = {"User-Agent": "base/1", "user-agent": "override/2"} + + sent = handshake(path, WebSocketOptions(additional_headers=extra)) + + assert values(sent, "user-agent") == [f"{USER_AGENT} override/2"] + assert extra == {"User-Agent": "base/1", "user-agent": "override/2"} + + @pytest.mark.parametrize("path", WS_PATHS) def test_default_options_send_the_same_header_names(path): without_options = handshake(path) From c85c07f6c1527f4ed9be576e509420fad268fdf0 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:58:36 -0800 Subject: [PATCH 5/9] test: pin that instrumented requests are sent under a span of their own --- tests/unit/test_tracing.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/unit/test_tracing.py b/tests/unit/test_tracing.py index cb42c5f..6a41ba6 100644 --- a/tests/unit/test_tracing.py +++ b/tests/unit/test_tracing.py @@ -186,3 +186,27 @@ def test_instrumentation_replaces_a_traceparent_set_by_hand_on_an_http_call( [traceparent] = values(http_server.requests[0], "traceparent") assert trace_id(traceparent) == span.get_span_context().trace_id + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_a_handshake_is_sent_under_a_span_of_its_own(tracer, path): + with ws_server(path) as (server, client), tracer.start_as_current_span("x") as span: + consume(open_stream(client, path, None)) + + [traceparent] = values(server.stop().header_list, "traceparent") + context = span.get_span_context() + assert trace_id(traceparent) == context.trace_id + # The parent id on the wire is the instrumentation's client span, a child + # of the caller's span, not the caller's span itself. + assert int(traceparent.split("-")[2], 16) != context.span_id + + +def test_an_http_call_is_sent_under_a_span_of_its_own(tracer, http_server): + client = sdk_client(http_server.url, False) + with tracer.start_as_current_span("request") as span: + client.tts.convert(text="hi") + + [traceparent] = values(http_server.requests[0], "traceparent") + context = span.get_span_context() + assert trace_id(traceparent) == context.trace_id + assert int(traceparent.split("-")[2], 16) != context.span_id From c4ce910cb5c17961e2ae1eb903e417d57777598f Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:49:09 -0800 Subject: [PATCH 6/9] docs: the hook example sets a timeout; say what the instrumentation needs The README's event-hook client had httpx's 5 s timeout. The tracing note now says a tracer provider is needed and when a hand-set traceparent is replaced; tests pin both. The handshake helper is private, and the test server's comments say what it records. --- README.md | 13 +++++++---- src/fishaudio/core/client_wrapper.py | 2 +- src/fishaudio/resources/asr.py | 6 +++--- src/fishaudio/resources/tts.py | 6 +++--- tests/unit/realtime_server.py | 4 +++- tests/unit/test_tracing.py | 32 ++++++++++++++++++++++------ tests/unit/test_websocket_headers.py | 24 ++++++++++++++++++++- 7 files changed, 68 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 6b8d681..b520919 100644 --- a/README.md +++ b/README.md @@ -315,9 +315,9 @@ audio = client.tts.convert( ## Tracing -To continue your trace in the Fish Audio API, send a W3C `traceparent` header on each request. Use one of the ways below; if the OpenTelemetry instrumentation is enabled, it replaces a `traceparent` you set yourself. +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**, 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. +**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 @@ -335,7 +335,7 @@ audio = client.tts.convert(text="Hello!", request_options=RequestOptions(additio 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): +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 @@ -343,7 +343,12 @@ import httpx def add_traceparent(request): request.headers["traceparent"] = current_traceparent() -client = FishAudio(httpx_client=httpx.Client(base_url="https://api.fish.audio", event_hooks={"request": [add_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 diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index a8e1cff..aadb111 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -210,7 +210,7 @@ def _prepare_request_kwargs( kwargs["params"] = params -def handshake_headers( +def _handshake_headers( client_wrapper: BaseClientWrapper, model: str, ws_options: Optional[WebSocketOptions], diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 686c665..da4ee1f 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -13,7 +13,7 @@ RequestOptions, WebSocketOptions, ) -from fishaudio.core.client_wrapper import handshake_headers +from fishaudio.core.client_wrapper import _handshake_headers from fishaudio.types import ( ASRContext, ASRRealtimeConfig, @@ -227,7 +227,7 @@ def audio_chunks(): ``` """ ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - headers = handshake_headers(self._client, model, ws_options) + headers = _handshake_headers(self._client, model, ws_options) client = self._client.client return ASRRealtimeStream( @@ -414,7 +414,7 @@ async def audio_chunks(): ``` """ ws_kwargs = ws_options.to_httpx_ws_kwargs() if ws_options else {} - headers = handshake_headers(self._client, model, ws_options) + headers = _handshake_headers(self._client, model, ws_options) client = self._client.client return AsyncASRRealtimeStream( diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 4cdc4af..b489e04 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -19,7 +19,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.client_wrapper import _handshake_headers from fishaudio.core.iterators import ( AsyncAudioStream, AsyncTTSTimestampStream, @@ -556,7 +556,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) + headers = _handshake_headers(self._client, model, ws_options) executor = ThreadPoolExecutor(max_workers=max_workers) @@ -1022,7 +1022,7 @@ 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) + headers = _handshake_headers(self._client, model, ws_options) ws: AsyncWebSocketSession async with aconnect_ws( diff --git a/tests/unit/realtime_server.py b/tests/unit/realtime_server.py index d6d76ce..61d8ef9 100644 --- a/tests/unit/realtime_server.py +++ b/tests/unit/realtime_server.py @@ -54,7 +54,9 @@ 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] = {} - # Every handshake header line in order, repeated names included. + # 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]] = [] diff --git a/tests/unit/test_tracing.py b/tests/unit/test_tracing.py index 6a41ba6..33bc080 100644 --- a/tests/unit/test_tracing.py +++ b/tests/unit/test_tracing.py @@ -136,13 +136,15 @@ def _hooked_client(url, is_async): async def ahook(request): request.headers["traceparent"] = "from-hook" - http = httpx.AsyncClient(base_url=url, event_hooks={"request": [ahook]}) + http = httpx.AsyncClient( + base_url=url, timeout=240.0, event_hooks={"request": [ahook]} + ) return AsyncFishAudio(api_key="test-key", httpx_client=http) def hook(request): request.headers["traceparent"] = "from-hook" - http = httpx.Client(base_url=url, event_hooks={"request": [hook]}) + http = httpx.Client(base_url=url, timeout=240.0, event_hooks={"request": [hook]}) return FishAudio(api_key="test-key", httpx_client=http) @@ -179,9 +181,11 @@ def test_instrumentation_replaces_a_traceparent_set_by_hand_on_a_handshake( def test_instrumentation_replaces_a_traceparent_set_by_hand_on_an_http_call( tracer, http_server ): - client = sdk_client(http_server.url, False) options = RequestOptions(additional_headers={"traceparent": MANUAL}) - with tracer.start_as_current_span("request") as span: + with ( + sdk_client(http_server.url, False) as client, + tracer.start_as_current_span("request") as span, + ): client.tts.convert(text="hi", request_options=options) [traceparent] = values(http_server.requests[0], "traceparent") @@ -202,11 +206,27 @@ def test_a_handshake_is_sent_under_a_span_of_its_own(tracer, path): def test_an_http_call_is_sent_under_a_span_of_its_own(tracer, http_server): - client = sdk_client(http_server.url, False) - with tracer.start_as_current_span("request") as span: + with ( + sdk_client(http_server.url, False) as client, + tracer.start_as_current_span("request") as span, + ): client.tts.convert(text="hi") [traceparent] = values(http_server.requests[0], "traceparent") context = span.get_span_context() assert trace_id(traceparent) == context.trace_id assert int(traceparent.split("-")[2], 16) != context.span_id + + +def test_without_a_tracer_provider_a_traceparent_set_by_hand_is_sent_as_is( + http_server, +): + HTTPXClientInstrumentor().instrument() + try: + options = RequestOptions(additional_headers={"traceparent": MANUAL}) + with sdk_client(http_server.url, False) as client: + client.tts.convert(text="hi", request_options=options) + finally: + HTTPXClientInstrumentor().uninstrument() + + assert values(http_server.requests[0], "traceparent") == [MANUAL] diff --git a/tests/unit/test_websocket_headers.py b/tests/unit/test_websocket_headers.py index 3277c46..fe502b2 100644 --- a/tests/unit/test_websocket_headers.py +++ b/tests/unit/test_websocket_headers.py @@ -11,7 +11,7 @@ def handshake(path, ws_options=None): - """The handshake's header lines, in order, as the server read them.""" + """The handshake's headers, in order, as the test server reports them.""" with ws_server(path) as (server, client): consume(open_stream(client, path, ws_options)) return server.stop().header_list @@ -77,3 +77,25 @@ def test_default_options_send_the_same_header_names(path): names = [name for name, _ in without_options] assert [name for name, _ in with_default_options] == names assert {"authorization", "user-agent", "model"} <= set(names) + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_the_default_handshake_headers(path): + """What a call without ws_options sends, written out.""" + sent = handshake(path) + + model = "transcribe-stream-1" if "asr" in path else "s2.1-pro" + assert [name for name, _ in sent] == [ + "accept", + "accept-encoding", + "authorization", + "model", + "user-agent", + "connection", + "upgrade", + "sec-websocket-key", + "sec-websocket-version", + ] + assert values(sent, "authorization") == ["Bearer test-key"] + assert values(sent, "model") == [model] + assert values(sent, "user-agent") == [USER_AGENT] From 44676b84264d500c9a2feb2e336304b01795a051 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:21:54 -0800 Subject: [PATCH 7/9] feat(websocket): merge additional_headers as RequestOptions headers are merged An Authorization in WebSocketOptions.additional_headers now replaces the API key on the handshake, as one in RequestOptions does on an HTTP call. The handshake's model stays the method's argument. One on a supplied httpx client still does not replace the key. additional_headers is new in this branch, so nothing changes for existing callers. --- src/fishaudio/core/client_wrapper.py | 27 +++++++-------- src/fishaudio/core/websocket_options.py | 9 ++--- tests/unit/test_websocket_headers.py | 44 +++++++++++++++++++------ 3 files changed, 53 insertions(+), 27 deletions(-) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 92f1772..d047474 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -244,21 +244,22 @@ def _handshake_headers( model: str, ws_options: Optional[WebSocketOptions], ) -> httpx.Headers: - """Build the headers of a WebSocket handshake. + """Build the headers of a WebSocket handshake, as for an HTTP call. - ``ws_options.additional_headers`` come first; the SDK's own headers replace - any spelling of the same name. The exception is ``User-Agent``, which is - appended to the SDK's own, as on HTTP calls. + ``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 = dict((ws_options.additional_headers if ws_options else None) or {}) - own = {"model": model} - for name in list(additional): - if name.lower() == "user-agent": - # The last spelling wins, as in get_headers(). - own["User-Agent"] = additional.pop(name) - headers = httpx.Headers(additional) - headers.update(client_wrapper.get_headers(own)) - return headers + 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): diff --git a/src/fishaudio/core/websocket_options.py b/src/fishaudio/core/websocket_options.py index 595f828..861cb01 100644 --- a/src/fishaudio/core/websocket_options.py +++ b/src/fishaudio/core/websocket_options.py @@ -24,10 +24,11 @@ class WebSocketOptions: 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": ...}``. The headers the SDK sets itself - (``Authorization``, ``model``) are kept, whatever the casing of a - name given here; a ``User-Agent`` given here is appended to the - SDK's own. The dict is not modified. + 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. ``model`` is always the + method's argument. The dict is not modified. Note: Descriptions of the httpx_ws options adapted from httpx_ws documentation. diff --git a/tests/unit/test_websocket_headers.py b/tests/unit/test_websocket_headers.py index fe502b2..c8528fa 100644 --- a/tests/unit/test_websocket_headers.py +++ b/tests/unit/test_websocket_headers.py @@ -1,7 +1,9 @@ """WebSocketOptions.additional_headers, checked on the handshake each path sends.""" +import httpx import pytest +from fishaudio import AsyncFishAudio, FishAudio from fishaudio.core import WebSocketOptions from fishaudio.core.client_wrapper import USER_AGENT @@ -33,19 +35,41 @@ def test_additional_headers_are_sent_on_the_handshake(path): @pytest.mark.parametrize("path", WS_PATHS) -def test_sdk_headers_win_over_additional_headers_in_any_casing(path): - default = handshake(path) - +def test_an_authorization_in_additional_headers_replaces_the_key_in_any_casing( + path, +): sent = handshake( - path, - WebSocketOptions( - additional_headers={"AUTHORIZATION": "Bearer other", "Model": "other"} - ), + path, WebSocketOptions(additional_headers={"AUTHORIZATION": "Bearer other"}) ) - for name in ("authorization", "model"): - assert values(sent, name) == values(default, name) - assert values(sent, "authorization") == ["Bearer test-key"] + assert values(sent, "authorization") == ["Bearer other"] + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_model_is_the_methods_argument_whatever_the_additional_headers_say(path): + default = handshake(path) + + sent = handshake(path, WebSocketOptions(additional_headers={"Model": "other"})) + + assert values(sent, "model") == values(default, "model") + + +@pytest.mark.parametrize("path", WS_PATHS) +def test_an_authorization_on_a_supplied_httpx_client_does_not_replace_the_key( + path, +): + def make_client(url, is_async): + headers = {"Authorization": "Bearer client"} + if is_async: + http = httpx.AsyncClient(base_url=url, headers=headers) + return AsyncFishAudio(api_key="test-key", httpx_client=http) + http = httpx.Client(base_url=url, headers=headers) + return FishAudio(api_key="test-key", httpx_client=http) + + with ws_server(path, make_client) as (server, client): + consume(open_stream(client, path)) + + assert values(server.stop().header_list, "authorization") == ["Bearer test-key"] @pytest.mark.parametrize("path", WS_PATHS) From a612be6a1f49cda5d8342db5e0308ef5a4d457ee Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:59:25 -0800 Subject: [PATCH 8/9] fix(headers): send an Authorization given in two spellings once get_headers() replaced the SDK's Authorization with the caller's but kept every spelling the caller gave, so {"Authorization": a, "authorization": b} was sent as two Authorization headers on HTTP calls and on the WebSocket handshake. The last one given is now sent, as for User-Agent. --- src/fishaudio/core/client_wrapper.py | 15 ++++++++++---- src/fishaudio/core/websocket_options.py | 5 +++-- tests/unit/test_core.py | 27 +++++++++++++++++++++++++ tests/unit/test_websocket_headers.py | 15 ++++++++++++++ 4 files changed, 56 insertions(+), 6 deletions(-) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index d047474..d95c51e 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -191,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 @@ -200,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) diff --git a/src/fishaudio/core/websocket_options.py b/src/fishaudio/core/websocket_options.py index 861cb01..710542e 100644 --- a/src/fishaudio/core/websocket_options.py +++ b/src/fishaudio/core/websocket_options.py @@ -27,8 +27,9 @@ class WebSocketOptions: 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. ``model`` is always the - method's argument. The dict is not modified. + 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: Descriptions of the httpx_ws options adapted from httpx_ws documentation. diff --git a/tests/unit/test_core.py b/tests/unit/test_core.py index 5f20d72..6b8b9d7 100644 --- a/tests/unit/test_core.py +++ b/tests/unit/test_core.py @@ -201,6 +201,33 @@ def handler(request: httpx.Request) -> httpx.Response: wrapper.request("GET", "/x") assert seen == [["Bearer other"], [f"Bearer {mock_api_key}"]] + @pytest.mark.parametrize( + ("given", "expected"), + [ + ({"Authorization": "Bearer a", "authorization": "Bearer b"}, "Bearer b"), + ({"authorization": "Bearer b", "AUTHORIZATION": "Bearer a"}, "Bearer a"), + ], + ) + def test_authorization_in_two_spellings_is_sent_once_the_last_one_given( + self, mock_api_key, given, expected + ): + seen = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request.headers.get_list("authorization")) + return httpx.Response(200, json={}) + + http = httpx.Client( + base_url="https://api.test", transport=httpx.MockTransport(handler) + ) + wrapper = ClientWrapper(api_key=mock_api_key, httpx_client=http) + before = dict(given) + wrapper.request( + "GET", "/x", request_options=RequestOptions(additional_headers=given) + ) + assert seen == [[expected]] + assert given == before + def test_additional_user_agent_is_sent_once_after_the_sdk_one(self, mock_api_key): wrapper = ClientWrapper(api_key=mock_api_key) headers = wrapper.get_headers({"user-agent": "mine"}) diff --git a/tests/unit/test_websocket_headers.py b/tests/unit/test_websocket_headers.py index c8528fa..81965de 100644 --- a/tests/unit/test_websocket_headers.py +++ b/tests/unit/test_websocket_headers.py @@ -45,6 +45,21 @@ def test_an_authorization_in_additional_headers_replaces_the_key_in_any_casing( assert values(sent, "authorization") == ["Bearer other"] +@pytest.mark.parametrize("path", WS_PATHS) +def test_an_authorization_in_two_spellings_is_sent_once_the_last_one_given(path): + extra = {"Authorization": "Bearer old", "authorization": "Bearer new"} + + sent = handshake(path, WebSocketOptions(additional_headers=extra)) + + assert values(sent, "authorization") == ["Bearer new"] + assert extra == {"Authorization": "Bearer old", "authorization": "Bearer new"} + + reversed_order = {"authorization": "Bearer new", "Authorization": "Bearer old"} + sent = handshake(path, WebSocketOptions(additional_headers=reversed_order)) + + assert values(sent, "authorization") == ["Bearer old"] + + @pytest.mark.parametrize("path", WS_PATHS) def test_model_is_the_methods_argument_whatever_the_additional_headers_say(path): default = handshake(path) From 98bf75bc5531f4ab3d4923ccf8bae93e43dd7a1d Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 03:19:53 -0800 Subject: [PATCH 9/9] test(core): cover additional_query_params on requests Codecov's patch check counted the query-params block of _prepare_request_kwargs as new lines once main had moved it; no test had ever run it. Cover it with and without method params. --- tests/unit/test_core.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/unit/test_core.py b/tests/unit/test_core.py index 6b8b9d7..6460c53 100644 --- a/tests/unit/test_core.py +++ b/tests/unit/test_core.py @@ -237,6 +237,39 @@ def test_additional_user_agent_is_sent_once_after_the_sdk_one(self, mock_api_key assert sent["User-Agent"].endswith(" mine") +class TestRequestQueryParams: + """RequestOptions.additional_query_params reach the request URL.""" + + @pytest.mark.parametrize( + ("method_params", "expected"), + [ + (None, {"extra": "1"}), + ({"page_size": "10"}, {"page_size": "10", "extra": "1"}), + ], + ) + def test_additional_query_params_are_sent( + self, mock_api_key, method_params, expected + ): + seen = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(dict(request.url.params)) + return httpx.Response(200, json={}) + + http = httpx.Client( + base_url="https://api.test", transport=httpx.MockTransport(handler) + ) + wrapper = ClientWrapper(api_key=mock_api_key, httpx_client=http) + kwargs = {} if method_params is None else {"params": method_params} + wrapper.request( + "GET", + "/x", + request_options=RequestOptions(additional_query_params={"extra": "1"}), + **kwargs, + ) + assert seen == [expected] + + class TestAsyncClientWrapper: """Test async AsyncClientWrapper."""