From ee4a69be9caec290cf208d634bcf72f87c715bcf Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:06:23 -0800 Subject: [PATCH 1/3] feat: send User-Agent fish-audio-python/, appending a caller's value All Fish Audio SDKs now send `fish-audio-/`, one RFC 9110 product (`fish-audio/python/` is not: a product cannot contain "/"). - `fishaudio`: every HTTP request and the TTS and realtime ASR WebSocket handshakes (sync and async) send `fish-audio-python/`. - A User-Agent the caller sets, in `RequestOptions.additional_headers` (any casing) or on their own `httpx_client`, is appended after the SDK's product instead of replacing it, as in the other SDKs. httpx's default `python-httpx/...` is not appended. Before, a lowercase `user-agent` in additional headers was sent next to ours as a second header. - Legacy `fish_audio_sdk` sends `fish-audio-python/ (legacy)` instead of `fish-audio/python/legacy`: the version is now real and "legacy" is an RFC 9110 comment. Tests check the format, RFC 9110 grammar, that __version__ matches pyproject.toml, every HTTP endpoint type on a local server, error responses, both WebSocket handshakes against the realtime test server (refused with 401), and the legacy clients. Co-Authored-By: Claude Opus 5.5 --- src/fish_audio_sdk/io.py | 10 +- src/fish_audio_sdk/websocket.py | 5 +- src/fishaudio/core/client_wrapper.py | 64 +++++-- tests/unit/test_asr_realtime.py | 2 + tests/unit/test_tts_realtime.py | 4 +- tests/unit/test_user_agent.py | 253 +++++++++++++++++++++++++++ 6 files changed, 321 insertions(+), 17 deletions(-) create mode 100644 tests/unit/test_user_agent.py diff --git a/src/fish_audio_sdk/io.py b/src/fish_audio_sdk/io.py index 304dadb..6d5935d 100644 --- a/src/fish_audio_sdk/io.py +++ b/src/fish_audio_sdk/io.py @@ -16,8 +16,14 @@ import httpx._types from typing_extensions import Concatenate, ParamSpec +from fishaudio.core.client_wrapper import USER_AGENT + from .exceptions import HttpCodeErr +# The SDK's product with a comment that marks the legacy API (RFC 9110: +# product *( RWS ( product / comment ) )), so the version stays parseable. +LEGACY_USER_AGENT = f"{USER_AGENT} (legacy)" + class RemoteCall: _base_url: str @@ -35,7 +41,7 @@ def init_async_client(self): base_url=self._base_url, headers={ "Authorization": f"Bearer {self._apikey}", - "User-Agent": "fish-audio/python/legacy", + "User-Agent": LEGACY_USER_AGENT, }, timeout=None, ) @@ -45,7 +51,7 @@ def init_sync_client(self): base_url=self._base_url, headers={ "Authorization": f"Bearer {self._apikey}", - "User-Agent": "fish-audio/python/legacy", + "User-Agent": LEGACY_USER_AGENT, }, timeout=None, ) diff --git a/src/fish_audio_sdk/websocket.py b/src/fish_audio_sdk/websocket.py index 37dbd12..eb0065f 100644 --- a/src/fish_audio_sdk/websocket.py +++ b/src/fish_audio_sdk/websocket.py @@ -9,6 +9,7 @@ from fishaudio.core._ws_utils import drain_reader from .exceptions import WebSocketErr +from .io import LEGACY_USER_AGENT from .schemas import Backends, CloseEvent, StartEvent, TextEvent, TTSRequest @@ -27,7 +28,7 @@ def __init__( base_url=self._base_url, headers={ "Authorization": f"Bearer {self._apikey}", - "User-Agent": "fish-audio/python/legacy", + "User-Agent": LEGACY_USER_AGENT, }, ) @@ -106,7 +107,7 @@ def __init__( base_url=self._base_url, headers={ "Authorization": f"Bearer {self._apikey}", - "User-Agent": "fish-audio/python/legacy", + "User-Agent": LEGACY_USER_AGENT, }, ) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index be74c73..c77daa4 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -2,7 +2,7 @@ import os from json import JSONDecodeError -from typing import Any, Optional +from typing import Any, Optional, Union import httpx @@ -48,9 +48,43 @@ def _raise_for_status(response: httpx.Response) -> None: raise _api_error(status, message, response.text) +USER_AGENT = f"fish-audio-python/{__version__}" +"""The SDK's product, ``fish-audio-/``: the format every Fish +Audio SDK sends, so the API can tell which SDK and version made a request.""" + +_HTTPX_DEFAULT_USER_AGENT = "python-httpx/" + + +def user_agent(caller: Optional[str] = None) -> str: + """Return the User-Agent to send: the SDK's product, then ``caller`` if set. + + A caller's value is appended rather than allowed to replace the SDK's, so an + app can name itself without hiding which SDK made the request. A value that + already starts with the SDK's product is not doubled. + """ + value = (caller or "").strip() + if value == USER_AGENT or value.startswith(f"{USER_AGENT} "): + value = value[len(USER_AGENT) :].strip() + return f"{USER_AGENT} {value}" if value else USER_AGENT + + +def _caller_user_agent( + client: Union[httpx.Client, httpx.AsyncClient, None], +) -> Optional[str]: + """The User-Agent set on a user's own httpx client, unless it is httpx's default.""" + if client is None: + return None + value = client.headers.get("user-agent") + if not value or value.startswith(_HTTPX_DEFAULT_USER_AGENT): + return None + return value + + class BaseClientWrapper: """Base wrapper with shared logic for sync/async clients.""" + _client_user_agent: Optional[str] = None + def __init__( self, *, @@ -67,13 +101,19 @@ def __init__( def get_headers( self, additional_headers: Optional[dict[str, str]] = None ) -> dict[str, str]: - """Build headers including authentication and user agent.""" - headers = { - "Authorization": f"Bearer {self.api_key}", - "User-Agent": f"fish-audio/python/{__version__}", - } - if additional_headers: - headers.update(additional_headers) + """Build headers including authentication and user agent. + + A ``User-Agent`` in ``additional_headers`` (any casing), or else one set + on a user-supplied httpx client, is appended to the SDK's own. + """ + headers = {"Authorization": f"Bearer {self.api_key}"} + caller = self._client_user_agent + for name, value in (additional_headers or {}).items(): + if name.lower() == "user-agent": + caller = value + else: + headers[name] = value + headers["User-Agent"] = user_agent(caller) return headers def _prepare_request_kwargs( @@ -81,9 +121,9 @@ def _prepare_request_kwargs( ) -> None: """Prepare request kwargs by merging headers, timeout, and query params.""" # Merge headers - headers = self.get_headers() - if request_options and request_options.additional_headers: - headers.update(request_options.additional_headers) + headers = self.get_headers( + request_options.additional_headers if request_options else None + ) # Headers set by the calling method win, whatever the case of the name: # {"Model": ...} from request options must not travel next to {"model": ...}. explicit = kwargs.get("headers", {}) @@ -120,6 +160,7 @@ def __init__( if httpx_client is not None: self._client = httpx_client + self._client_user_agent = _caller_user_agent(httpx_client) else: self._client = httpx.Client( base_url=base_url, @@ -210,6 +251,7 @@ def __init__( if httpx_client is not None: self._client = httpx_client + self._client_user_agent = _caller_user_agent(httpx_client) else: self._client = httpx.AsyncClient( base_url=base_url, diff --git a/tests/unit/test_asr_realtime.py b/tests/unit/test_asr_realtime.py index 20941bb..d0542a3 100644 --- a/tests/unit/test_asr_realtime.py +++ b/tests/unit/test_asr_realtime.py @@ -22,6 +22,7 @@ FishAudio, WebSocketError, ) +from fishaudio.core.client_wrapper import USER_AGENT from fishaudio.resources import asr_realtime from fishaudio.resources.asr import _realtime_config from fishaudio.resources.asr_realtime import ( @@ -397,6 +398,7 @@ def test_streams_audio_and_yields_typed_events(self): assert conn.path == "/v1/asr/realtime" assert conn.headers["authorization"] == "Bearer test-key" assert conn.headers["model"] == "transcribe-stream-1" + assert conn.headers["user-agent"] == USER_AGENT assert conn.received == [ { "type": "config", diff --git a/tests/unit/test_tts_realtime.py b/tests/unit/test_tts_realtime.py index 0a25e62..9e2a425 100644 --- a/tests/unit/test_tts_realtime.py +++ b/tests/unit/test_tts_realtime.py @@ -20,7 +20,7 @@ def mock_client_wrapper(mock_api_key): # Mock get_headers to return a dict with the additional headers merged wrapper.get_headers = lambda additional=None: { "Authorization": f"Bearer {mock_api_key}", - "User-Agent": "fish-audio/python/test", + "User-Agent": "fish-audio-python/test", **(additional or {}), } return wrapper @@ -36,7 +36,7 @@ def async_mock_client_wrapper(mock_api_key): # Mock get_headers to return a dict with the additional headers merged wrapper.get_headers = lambda additional=None: { "Authorization": f"Bearer {mock_api_key}", - "User-Agent": "fish-audio/python/test", + "User-Agent": "fish-audio-python/test", **(additional or {}), } return wrapper diff --git a/tests/unit/test_user_agent.py b/tests/unit/test_user_agent.py new file mode 100644 index 0000000..f46f0da --- /dev/null +++ b/tests/unit/test_user_agent.py @@ -0,0 +1,253 @@ +"""The SDK sends ``User-Agent: fish-audio-python/`` on every path.""" + +from __future__ import annotations + +import contextlib +import re +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import TYPE_CHECKING + +import httpx +import pytest + +from fishaudio import AsyncFishAudio, FishAudio, __version__ +from fishaudio.core import ClientWrapper, RequestOptions +from fishaudio.core.client_wrapper import USER_AGENT, user_agent +from fishaudio.exceptions import APIError + +from .realtime_server import RealtimeServer + +if TYPE_CHECKING: + from collections.abc import Iterator + +# RFC 9110 section 5.6.2: tchar; a product is token ["/" product-version]. +TCHAR = r"[!#$%&'*+\-.^_`|~0-9A-Za-z]" +PRODUCT = re.compile(rf"^{TCHAR}+/{TCHAR}+$") + + +class TestFormat: + def test_product_is_fish_audio_python_and_the_version(self): + assert f"fish-audio-python/{__version__}" == USER_AGENT + + def test_product_is_valid_rfc_9110_grammar(self): + assert PRODUCT.match(USER_AGENT), USER_AGENT + + def test_version_matches_pyproject(self): + pyproject = (Path(__file__).parents[2] / "pyproject.toml").read_text() + match = re.search(r'^version = "([^"]+)"', pyproject, re.MULTILINE) + assert match is not None + assert __version__ == match.group(1) + + +class TestUserAgentValue: + def test_alone(self): + assert user_agent() == USER_AGENT + assert user_agent(" ") == USER_AGENT + + def test_caller_value_is_appended(self): + assert user_agent("my-app/1.0") == f"{USER_AGENT} my-app/1.0" + + def test_not_doubled(self): + assert user_agent(USER_AGENT) == USER_AGENT + assert user_agent(f"{USER_AGENT} my-app/1.0") == f"{USER_AGENT} my-app/1.0" + + +class TestGetHeaders: + def test_additional_user_agent_of_any_casing_is_appended_once(self): + headers = ClientWrapper(api_key="k").get_headers({"user-agent": "my-app/1.0"}) + names = [name for name in headers if name.lower() == "user-agent"] + assert names == ["User-Agent"] + assert headers["User-Agent"] == f"{USER_AGENT} my-app/1.0" + + def test_user_agent_of_a_user_httpx_client_is_appended(self): + client = httpx.Client(headers={"User-Agent": "my-app/1.0"}) + wrapper = ClientWrapper(api_key="k", httpx_client=client) + assert wrapper.get_headers()["User-Agent"] == f"{USER_AGENT} my-app/1.0" + # A request option replaces the client's value. + headers = wrapper.get_headers({"User-Agent": "my-script/2.0"}) + assert headers["User-Agent"] == f"{USER_AGENT} my-script/2.0" + + def test_httpx_default_user_agent_is_not_appended(self): + wrapper = ClientWrapper(api_key="k", httpx_client=httpx.Client()) + assert wrapper.get_headers()["User-Agent"] == USER_AGENT + + +class _Recorder(BaseHTTPRequestHandler): + """Records each request's User-Agent values and answers with ``status``.""" + + seen: list[tuple[str, str, list[str]]] + status = 200 + + def _answer(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + self.rfile.read(length) + type(self).seen.append( + (self.command, self.path, self.headers.get_all("User-Agent") or []) + ) + if self.path.startswith("/v1/tts") and self.status == 200: + body, content_type = b"\x01\x02", "audio/mpeg" + elif self.path.startswith("/model") and self.command == "GET": + body, content_type = b'{"items": [], "total": 0}', "application/json" + elif self.path.startswith("/v1/asr"): + body, content_type = ( + b'{"text": "", "duration": 0, "segments": []}', + "application/json", + ) + else: + body, content_type = ( + b'{"_id": "c", "user_id": "u", "credit": "1",' + b' "created_at": "2026-01-01", "updated_at": "2026-01-01"}', + "application/json", + ) + if self.status != 200: + body, content_type = b'{"message": "nope"}', "application/json" + self.send_response(self.status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + do_GET = do_POST = do_PATCH = do_DELETE = _answer + + def log_message(self, *args): # silence + pass + + +@contextlib.contextmanager +def recording_server(status: int = 200) -> Iterator[tuple[str, list]]: + handler = type("Handler", (_Recorder,), {"seen": [], "status": status}) + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}", handler.seen + finally: + server.shutdown() + server.server_close() + + +class TestHTTP: + def test_every_endpoint_type_sends_it_once(self): + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + client.account.get_credits() + client.voices.list() + client.tts.convert(text="hi") + client.asr.transcribe(audio=b"\x00\x01") + client.close() + assert len(seen) == 4 + for method, path, values in seen: + assert values == [USER_AGENT], f"{method} {path}" + + def test_request_options_user_agent_is_appended(self): + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + client.account.get_credits( + request_options=RequestOptions( + additional_headers={"user-agent": "my-app/1.0"} + ) + ) + client.close() + assert seen[0][2] == [f"{USER_AGENT} my-app/1.0"] + + def test_user_httpx_client_user_agent_is_appended(self): + with recording_server() as (url, seen): + own = httpx.Client(base_url=url, headers={"User-Agent": "my-app/1.0"}) + client = FishAudio(api_key="test-key", httpx_client=own) + client.account.get_credits() + own.close() + assert seen[0][2] == [f"{USER_AGENT} my-app/1.0"] + + def test_a_failing_request_sent_it_and_still_raises(self): + with recording_server(status=500) as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + with pytest.raises(APIError): + client.account.get_credits() + client.close() + assert seen[0][2] == [USER_AGENT] + + async def test_async_client_sends_it(self): + with recording_server() as (url, seen): + client = AsyncFishAudio(api_key="test-key", base_url=url) + await client.account.get_credits() + await client.voices.list() + await client.close() + assert [values for _, _, values in seen] == [[USER_AGENT], [USER_AGENT]] + + +@contextlib.contextmanager +def refusing_ws_server() -> Iterator[RealtimeServer]: + """A WebSocket server that records the handshake and refuses it with 401.""" + server = RealtimeServer(lambda conn: None, reject_status=401) + try: + yield server + finally: + server.close() + + +class TestWebSockets: + def test_tts_websocket_handshake(self): + with refusing_ws_server() as server: + client = FishAudio(api_key="test-key", base_url=server.url) + with pytest.raises(Exception): + for _ in client.tts.stream_websocket(iter(["hi"])): + pass + client.close() + conn = server.stop() + assert conn.path == "/v1/tts/live" + assert conn.headers["user-agent"] == USER_AGENT + + async def test_async_tts_websocket_handshake(self): + with refusing_ws_server() as server: + client = AsyncFishAudio(api_key="test-key", base_url=server.url) + + async def text(): + yield "hi" + + with pytest.raises(Exception): + async for _ in client.tts.stream_websocket(text()): + pass + await client.close() + conn = server.stop() + assert conn.headers["user-agent"] == USER_AGENT + + def test_asr_realtime_handshake_with_a_client_user_agent(self): + with refusing_ws_server() as server: + own = httpx.Client(base_url=server.url, headers={"User-Agent": "app/2"}) + client = FishAudio(api_key="test-key", httpx_client=own) + with pytest.raises(Exception): + for _ in client.asr.stream_websocket(iter([b"\x00\x00"])): + pass + own.close() + conn = server.stop() + assert conn.path == "/v1/asr/realtime" + assert conn.headers["user-agent"] == f"{USER_AGENT} app/2" + + async def test_async_asr_realtime_handshake(self): + with refusing_ws_server() as server: + client = AsyncFishAudio(api_key="test-key", base_url=server.url) + + async def audio(): + yield b"\x00\x00" + + with pytest.raises(Exception): + async for _ in client.asr.stream_websocket(audio()): + pass + await client.close() + conn = server.stop() + assert conn.headers["user-agent"] == USER_AGENT + + +class TestLegacy: + def test_legacy_package_sends_the_product_with_a_legacy_comment(self): + try: + from fish_audio_sdk import Session, WebSocketSession + except TypeError: + pytest.skip("fish_audio_sdk does not import on this Python version") + expected = f"{USER_AGENT} (legacy)" + session = Session("k") + assert session._sync_client.headers["user-agent"] == expected + assert session._async_client.headers["user-agent"] == expected + assert WebSocketSession("k")._client.headers["user-agent"] == expected From f4bc6a765dcf68a33020d081b90139677010d2d4 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:54:39 -0800 Subject: [PATCH 2/3] fix: keep a customised httpx User-Agent and read it on every request Review follow-ups on the User-Agent change: - A supplied httpx client whose User-Agent starts with httpx's product, such as `python-httpx/0.28.1 my-app/1.0`, lost the whole value. Only httpx's exact default (`python-httpx/`) is ignored now. - The supplied client's User-Agent was copied once, at construction, so a later change to the client's headers had no effect. get_headers() now reads it from the client on every call. Also adds tests that the new timestamps entry points (convert_with_timestamps, stream_with_timestamps, sync and async) send the header. Co-Authored-By: Claude Opus 5.5 --- src/fishaudio/core/client_wrapper.py | 20 +++++---- tests/unit/test_user_agent.py | 66 +++++++++++++++++++++++++++- 2 files changed, 76 insertions(+), 10 deletions(-) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index c77daa4..26caac6 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -52,7 +52,8 @@ def _raise_for_status(response: httpx.Response) -> None: """The SDK's product, ``fish-audio-/``: the format every Fish Audio SDK sends, so the API can tell which SDK and version made a request.""" -_HTTPX_DEFAULT_USER_AGENT = "python-httpx/" +# What httpx sends when nobody set a User-Agent; only this exact value is ignored. +_HTTPX_DEFAULT_USER_AGENT = f"python-httpx/{httpx.__version__}" def user_agent(caller: Optional[str] = None) -> str: @@ -71,11 +72,15 @@ def user_agent(caller: Optional[str] = None) -> str: def _caller_user_agent( client: Union[httpx.Client, httpx.AsyncClient, None], ) -> Optional[str]: - """The User-Agent set on a user's own httpx client, unless it is httpx's default.""" + """The User-Agent on an httpx client, unless it is httpx's unchanged default. + + A customised value that merely starts with httpx's product, such as + ``python-httpx/0.28.1 my-app/1.0``, is kept. + """ if client is None: return None value = client.headers.get("user-agent") - if not value or value.startswith(_HTTPX_DEFAULT_USER_AGENT): + if not value or value.strip() == _HTTPX_DEFAULT_USER_AGENT: return None return value @@ -83,8 +88,6 @@ def _caller_user_agent( class BaseClientWrapper: """Base wrapper with shared logic for sync/async clients.""" - _client_user_agent: Optional[str] = None - def __init__( self, *, @@ -107,7 +110,10 @@ def get_headers( on a user-supplied httpx client, is appended to the SDK's own. """ headers = {"Authorization": f"Bearer {self.api_key}"} - caller = self._client_user_agent + # Read from the client on every call, so a User-Agent changed on a + # supplied httpx client after construction is used. The SDK's own + # client carries USER_AGENT, which user_agent() does not double. + caller = _caller_user_agent(getattr(self, "_client", None)) for name, value in (additional_headers or {}).items(): if name.lower() == "user-agent": caller = value @@ -160,7 +166,6 @@ def __init__( if httpx_client is not None: self._client = httpx_client - self._client_user_agent = _caller_user_agent(httpx_client) else: self._client = httpx.Client( base_url=base_url, @@ -251,7 +256,6 @@ def __init__( if httpx_client is not None: self._client = httpx_client - self._client_user_agent = _caller_user_agent(httpx_client) else: self._client = httpx.AsyncClient( base_url=base_url, diff --git a/tests/unit/test_user_agent.py b/tests/unit/test_user_agent.py index f46f0da..63a7eb8 100644 --- a/tests/unit/test_user_agent.py +++ b/tests/unit/test_user_agent.py @@ -2,7 +2,9 @@ from __future__ import annotations +import base64 import contextlib +import json import re import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -13,7 +15,7 @@ import pytest from fishaudio import AsyncFishAudio, FishAudio, __version__ -from fishaudio.core import ClientWrapper, RequestOptions +from fishaudio.core import AsyncClientWrapper, ClientWrapper, RequestOptions from fishaudio.core.client_wrapper import USER_AGENT, user_agent from fishaudio.exceptions import APIError @@ -73,6 +75,36 @@ def test_httpx_default_user_agent_is_not_appended(self): wrapper = ClientWrapper(api_key="k", httpx_client=httpx.Client()) assert wrapper.get_headers()["User-Agent"] == USER_AGENT + def test_customised_value_starting_with_httpx_product_is_kept(self): + client = httpx.Client( + headers={"User-Agent": f"python-httpx/{httpx.__version__} my-app/1.0"} + ) + wrapper = ClientWrapper(api_key="k", httpx_client=client) + assert wrapper.get_headers()["User-Agent"] == ( + f"{USER_AGENT} python-httpx/{httpx.__version__} my-app/1.0" + ) + + def test_user_agent_changed_on_the_client_after_construction_is_used(self): + client = httpx.Client() + wrapper = ClientWrapper(api_key="k", httpx_client=client) + assert wrapper.get_headers()["User-Agent"] == USER_AGENT + client.headers["User-Agent"] = "my-app/2.0" + assert wrapper.get_headers()["User-Agent"] == f"{USER_AGENT} my-app/2.0" + del client.headers["User-Agent"] + assert wrapper.get_headers()["User-Agent"] == USER_AGENT + + async def test_async_wrapper_reads_the_client_user_agent_too(self): + client = httpx.AsyncClient() + wrapper = AsyncClientWrapper(api_key="k", httpx_client=client) + client.headers["User-Agent"] = "my-app/2.0" + assert wrapper.get_headers()["User-Agent"] == f"{USER_AGENT} my-app/2.0" + await client.aclose() + + def test_sdk_own_client_does_not_double_the_product(self): + wrapper = ClientWrapper(api_key="k") + assert wrapper.client.headers["User-Agent"] == USER_AGENT + assert wrapper.get_headers()["User-Agent"] == USER_AGENT + class _Recorder(BaseHTTPRequestHandler): """Records each request's User-Agent values and answers with ``status``.""" @@ -86,7 +118,17 @@ def _answer(self) -> None: type(self).seen.append( (self.command, self.path, self.headers.get_all("User-Agent") or []) ) - if self.path.startswith("/v1/tts") and self.status == 200: + if self.path.startswith("/v1/tts/stream/with-timestamp") and self.status == 200: + payload = { + "audio_base64": base64.b64encode(b"\x01").decode(), + "content": "hi", + "alignment": None, + "chunk_seq": 0, + "chunk_audio_offset_sec": 0.0, + } + body = f"event: message\r\ndata: {json.dumps(payload)}\r\n\r\n".encode() + content_type = "text/event-stream" + elif self.path.startswith("/v1/tts") and self.status == 200: body, content_type = b"\x01\x02", "audio/mpeg" elif self.path.startswith("/model") and self.command == "GET": body, content_type = b'{"items": [], "total": 0}', "application/json" @@ -141,6 +183,26 @@ def test_every_endpoint_type_sends_it_once(self): for method, path, values in seen: assert values == [USER_AGENT], f"{method} {path}" + def test_timestamps_entry_points_send_it(self): + with recording_server() as (url, seen): + client = FishAudio(api_key="test-key", base_url=url) + client.tts.convert_with_timestamps(text="hi") + client.tts.stream_with_timestamps(text="hi").collect() + client.close() + assert [(m, p, v) for m, p, v in seen] == [ + ("POST", "/v1/tts/stream/with-timestamp", [USER_AGENT]), + ("POST", "/v1/tts/stream/with-timestamp", [USER_AGENT]), + ] + + async def test_async_timestamps_entry_points_send_it(self): + with recording_server() as (url, seen): + client = AsyncFishAudio(api_key="test-key", base_url=url) + await client.tts.convert_with_timestamps(text="hi") + stream = await client.tts.stream_with_timestamps(text="hi") + await stream.collect() + await client.close() + assert [v for _, _, v in seen] == [[USER_AGENT], [USER_AGENT]] + def test_request_options_user_agent_is_appended(self): with recording_server() as (url, seen): client = FishAudio(api_key="test-key", base_url=url) From 6ece200cfbd6d1e7e278691aa8a10a2f5ac50c5b Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:01:21 -0800 Subject: [PATCH 3/3] feat: add the Python version and OS to the User-Agent as an RFC 9110 comment The User-Agent is now `fish-audio-python/ (python ; )`, e.g. `fish-audio-python/1.6.0 (python 3.12.1; linux)`, so we can see which Python versions users are on. The server still parses only the first product. A caller's User-Agent follows the comment; the legacy package adds a second comment: `fish-audio-python/1.6.0 (python 3.12.1; linux) (legacy)`. - The version comes from platform.python_version() and the OS from sys.platform, normalised to a short lowercase word (win32, cygwin and msys become windows; a trailing version such as freebsd14 is dropped). Nothing that identifies a person or machine is sent. - Every value keeps only its leading run of letters, digits and ._+- (at most 32 characters), else `unknown`, so no value can put (, ), \, whitespace or control characters into the header. - Computed once at import. Co-Authored-By: Claude Opus 5.5 --- src/fish_audio_sdk/io.py | 7 ++- src/fishaudio/core/client_wrapper.py | 58 ++++++++++++++++++++-- tests/unit/test_user_agent.py | 73 ++++++++++++++++++++++++++-- 3 files changed, 127 insertions(+), 11 deletions(-) diff --git a/src/fish_audio_sdk/io.py b/src/fish_audio_sdk/io.py index 6d5935d..e2ddb0c 100644 --- a/src/fish_audio_sdk/io.py +++ b/src/fish_audio_sdk/io.py @@ -20,8 +20,11 @@ from .exceptions import HttpCodeErr -# The SDK's product with a comment that marks the legacy API (RFC 9110: -# product *( RWS ( product / comment ) )), so the version stays parseable. +# The SDK's User-Agent, product and runtime comment, followed by a second +# comment that marks the legacy API. RFC 9110 allows several comments +# (product *( RWS ( product / comment ) )), and the runtime comment keeps the +# same shape as in the new SDK, e.g. +# fish-audio-python/1.6.0 (python 3.12.1; linux) (legacy). LEGACY_USER_AGENT = f"{USER_AGENT} (legacy)" diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 26caac6..31cbf7f 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -1,6 +1,9 @@ """HTTP client wrapper for managing requests and authentication.""" import os +import platform +import re +import sys from json import JSONDecodeError from typing import Any, Optional, Union @@ -48,20 +51,65 @@ def _raise_for_status(response: httpx.Response) -> None: raise _api_error(status, message, response.text) -USER_AGENT = f"fish-audio-python/{__version__}" +PRODUCT = f"fish-audio-python/{__version__}" """The SDK's product, ``fish-audio-/``: the format every Fish Audio SDK sends, so the API can tell which SDK and version made a request.""" +_SAFE_PREFIX = re.compile(r"[A-Za-z0-9._+-]+") + + +def _comment_value(value: object) -> str: + """Make a value safe inside an RFC 9110 comment. + + Keeps the leading run of letters, digits and ``._+-`` (at most 32 + characters) and drops the rest, so ``(``, ``)``, ``\\``, whitespace and + control characters never reach the header. Returns ``unknown`` when + nothing usable is left. + """ + if not isinstance(value, str): + return "unknown" + match = _SAFE_PREFIX.match(value.strip()) + return match.group(0)[:32] if match else "unknown" + + +def _os_family(sys_platform: object) -> str: + """The OS family as one short lowercase word: linux, darwin, windows, ...""" + os_name = _comment_value( + sys_platform.lower() if isinstance(sys_platform, str) else sys_platform + ) + if os_name in ("win32", "cygwin", "msys"): + return "windows" + # sys.platform carries a version on some systems, e.g. freebsd14. + return os_name.rstrip("0123456789") or "unknown" + + +def build_user_agent(python_version: object, sys_platform: object) -> str: + """Return ``fish-audio-python/ (python ; )``. + + Only the runtime, its version and the OS family are included: nothing + that identifies a person or machine. + """ + return ( + f"{PRODUCT} (python {_comment_value(python_version)}; " + f"{_os_family(sys_platform)})" + ) + + +USER_AGENT = build_user_agent(platform.python_version(), sys.platform) +"""The User-Agent the SDK sends, computed once at import, e.g. +``fish-audio-python/1.6.0 (python 3.12.1; linux)``.""" + # What httpx sends when nobody set a User-Agent; only this exact value is ignored. _HTTPX_DEFAULT_USER_AGENT = f"python-httpx/{httpx.__version__}" def user_agent(caller: Optional[str] = None) -> str: - """Return the User-Agent to send: the SDK's product, then ``caller`` if set. + """Return the User-Agent to send: the SDK's own, then ``caller`` if set. - A caller's value is appended rather than allowed to replace the SDK's, so an - app can name itself without hiding which SDK made the request. A value that - already starts with the SDK's product is not doubled. + 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. """ value = (caller or "").strip() if value == USER_AGENT or value.startswith(f"{USER_AGENT} "): diff --git a/tests/unit/test_user_agent.py b/tests/unit/test_user_agent.py index 63a7eb8..ffd65d5 100644 --- a/tests/unit/test_user_agent.py +++ b/tests/unit/test_user_agent.py @@ -5,7 +5,9 @@ import base64 import contextlib import json +import platform import re +import sys import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path @@ -16,7 +18,14 @@ from fishaudio import AsyncFishAudio, FishAudio, __version__ from fishaudio.core import AsyncClientWrapper, ClientWrapper, RequestOptions -from fishaudio.core.client_wrapper import USER_AGENT, user_agent +from fishaudio.core.client_wrapper import ( + PRODUCT, + USER_AGENT, + _comment_value, + _os_family, + build_user_agent, + user_agent, +) from fishaudio.exceptions import APIError from .realtime_server import RealtimeServer @@ -26,15 +35,24 @@ # RFC 9110 section 5.6.2: tchar; a product is token ["/" product-version]. TCHAR = r"[!#$%&'*+\-.^_`|~0-9A-Za-z]" -PRODUCT = re.compile(rf"^{TCHAR}+/{TCHAR}+$") +PRODUCT_GRAMMAR = re.compile(rf"^{TCHAR}+/{TCHAR}+$") +# product, then one or more comments with nothing RFC 9110 ctext excludes. +USER_AGENT_GRAMMAR = re.compile(rf"^{TCHAR}+/{TCHAR}+( \([^()\\\x00-\x1f\x7f]*\))+$") class TestFormat: def test_product_is_fish_audio_python_and_the_version(self): - assert f"fish-audio-python/{__version__}" == USER_AGENT + assert f"fish-audio-python/{__version__}" == PRODUCT def test_product_is_valid_rfc_9110_grammar(self): - assert PRODUCT.match(USER_AGENT), USER_AGENT + assert PRODUCT_GRAMMAR.match(PRODUCT), PRODUCT + + def test_user_agent_names_python_its_version_and_the_os(self): + expected_os = _os_family(sys.platform) + assert ( + f"{PRODUCT} (python {platform.python_version()}; {expected_os})" + ) == USER_AGENT + assert USER_AGENT_GRAMMAR.match(USER_AGENT), USER_AGENT def test_version_matches_pyproject(self): pyproject = (Path(__file__).parents[2] / "pyproject.toml").read_text() @@ -43,6 +61,52 @@ def test_version_matches_pyproject(self): assert __version__ == match.group(1) +class TestRuntimeComment: + def test_shape(self): + assert ( + build_user_agent("3.12.1", "linux") == f"{PRODUCT} (python 3.12.1; linux)" + ) + + @pytest.mark.parametrize( + ("sys_platform", "expected"), + [ + ("linux", "linux"), + ("darwin", "darwin"), + ("win32", "windows"), + ("cygwin", "windows"), + ("freebsd14", "freebsd"), + ("Emscripten", "emscripten"), + (None, "unknown"), + ("", "unknown"), + ], + ) + def test_os_family(self, sys_platform, expected): + assert _os_family(sys_platform) == expected + + @pytest.mark.parametrize( + "hostile", + [ + "3.12.1 (evil)", + "3.12.1)", + "3.12.1\\(", + "3.12.1\r\nX-Injected: 1", + "3.12.1\x00", + "3.12.1; host=alice-laptop", + "3.12.1 /home/alice", + ], + ) + def test_odd_values_are_cut_to_their_safe_prefix(self, hostile): + assert _comment_value(hostile) == "3.12.1" + assert USER_AGENT_GRAMMAR.match(build_user_agent(hostile, hostile)) + + def test_nothing_usable_becomes_unknown(self): + assert _comment_value("(x)") == "unknown" + assert _comment_value("\\") == "unknown" + assert _comment_value("") == "unknown" + assert _comment_value(None) == "unknown" + assert _comment_value("1" * 100) == "1" * 32 + + class TestUserAgentValue: def test_alone(self): assert user_agent() == USER_AGENT @@ -309,6 +373,7 @@ def test_legacy_package_sends_the_product_with_a_legacy_comment(self): except TypeError: pytest.skip("fish_audio_sdk does not import on this Python version") expected = f"{USER_AGENT} (legacy)" + assert USER_AGENT_GRAMMAR.match(expected) session = Session("k") assert session._sync_client.headers["user-agent"] == expected assert session._async_client.headers["user-agent"] == expected