From a46f3e703a6f552a244908d382793b88c3d097b2 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:30:47 -0800 Subject: [PATCH 01/13] fix: ship py.typed in the fishaudio package Only the legacy fish_audio_sdk package had the PEP 561 marker, so mypy skipped fishaudio as untyped (import-untyped) and checked none of the calls into it. --- src/fishaudio/py.typed | 0 tests/unit/test_type_hints.py | 7 +++++++ 2 files changed, 7 insertions(+) create mode 100644 src/fishaudio/py.typed diff --git a/src/fishaudio/py.typed b/src/fishaudio/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/test_type_hints.py b/tests/unit/test_type_hints.py index 1fa5315..c05e44f 100644 --- a/tests/unit/test_type_hints.py +++ b/tests/unit/test_type_hints.py @@ -1,10 +1,12 @@ """Annotations on the public stream classes resolve at runtime.""" import typing +from pathlib import Path import pytest from typing_extensions import Self +import fishaudio from fishaudio.core.iterators import ( AsyncAudioStream, AsyncTTSTimestampStream, @@ -57,3 +59,8 @@ def test_stream_method_annotations_resolve(method): ) def test_enter_methods_resolve_to_self(method): assert typing.get_type_hints(method) == {"return": Self} + + +def test_package_is_marked_as_typed(): + """PEP 561: without py.typed, mypy reports the installed package as untyped.""" + assert (Path(fishaudio.__file__).parent / "py.typed").is_file() From 2a21cb025cec14129c3b9663e89390167cae021d Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:31:39 -0800 Subject: [PATCH 02/13] docs: make the client, error handling and play() examples match the SDK - help(FishAudio): tts.convert returns bytes; write them, do not iterate them as chunks. help(AsyncFishAudio): await convert, import asyncio. - README error handling caught fishaudio.exceptions.ValidationError, which the SDK never raises. It now catches APIError for other error responses (the API answers an invalid request with 400) and says that values checked locally raise pydantic's ValidationError. - play(): a missing ffplay raises DependencyError; only an ffplay that fails falls back to sounddevice. --- README.md | 11 +++++++---- src/fishaudio/client.py | 12 ++++++------ src/fishaudio/utils/play.py | 9 ++++++--- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index bf3ee90..94b4d84 100644 --- a/README.md +++ b/README.md @@ -377,9 +377,9 @@ client = FishAudio(httpx_client=http_client) ```python from fishaudio.exceptions import ( + APIError, AuthenticationError, RateLimitError, - ValidationError, FishAudioError, ) @@ -389,12 +389,15 @@ except AuthenticationError: print("Invalid API key") except RateLimitError: print("Rate limit exceeded") -except ValidationError as e: - print(f"Invalid request: {e}") +except APIError as e: + # Any other error response, such as 400 for a request the API rejects + print(f"API error {e.status}: {e.message}") except FishAudioError as e: - print(f"API error: {e}") + print(f"Error: {e}") ``` +A value the SDK can check before sending, such as a `speed` outside 0.5 to 2.0, raises pydantic's `ValidationError` instead, and no request is sent. `fishaudio.exceptions.ValidationError` is not raised by the SDK. + Every `APIError` carries the headers of the error response. When you contact support, include the trace id and the error code. Either can be absent. ```python diff --git a/src/fishaudio/client.py b/src/fishaudio/client.py index 11f2aa2..2398ae6 100644 --- a/src/fishaudio/client.py +++ b/src/fishaudio/client.py @@ -30,8 +30,7 @@ class FishAudio: # Generate speech audio = client.tts.convert(text="Hello world") with open("output.mp3", "wb") as f: - for chunk in audio: - f.write(chunk) + f.write(audio) # List voices voices = client.voices.list(page_size=20) @@ -114,16 +113,17 @@ class AsyncFishAudio: Example: ```python + import asyncio + from fishaudio import AsyncFishAudio async def main(): client = AsyncFishAudio(api_key="your_api_key") # Generate speech - audio = client.tts.convert(text="Hello world") - async with aiofiles.open("output.mp3", "wb") as f: - async for chunk in audio: - await f.write(chunk) + audio = await client.tts.convert(text="Hello world") + with open("output.mp3", "wb") as f: + f.write(audio) # List voices voices = await client.voices.list(page_size=20) diff --git a/src/fishaudio/utils/play.py b/src/fishaudio/utils/play.py index 4ff25b3..601836f 100644 --- a/src/fishaudio/utils/play.py +++ b/src/fishaudio/utils/play.py @@ -26,10 +26,13 @@ def play( Args: audio: Audio bytes or iterable of bytes notebook: Use Jupyter notebook playback (IPython.display.Audio) - use_ffmpeg: Use ffplay for playback (default, falls back to sounddevice) + use_ffmpeg: Play with ffplay (the default). If ffplay is not + installed, DependencyError is raised; there is no fallback. If + ffplay is installed but fails, playback falls back to sounddevice. + False plays with sounddevice (the ``[utils]`` extra). Raises: - DependencyError: If required playback tool is not installed + DependencyError: If the playback tool to use is not installed Examples: ```python @@ -44,7 +47,7 @@ def play( # In Jupyter notebook play(audio, notebook=True) - # Force sounddevice fallback + # Play with sounddevice instead of ffplay play(audio, use_ffmpeg=False) ``` """ From 2d8275688f0d5392f5bedc5710a0d2ecf062c4de Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:07:22 -0800 Subject: [PATCH 03/13] fix(errors): SDK errors survive pickling APIError and its subclasses, and DependencyError, take more than one argument, so pickle (used by worker pools and multiprocessing) could not rebuild them from the formatted message and raised TypeError. They now pickle with their status, message, body and headers. --- src/fishaudio/exceptions.py | 11 +++++++++++ tests/unit/test_error_headers.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index 00a9c01..05c2f44 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -38,6 +38,14 @@ def __init__( self.headers = httpx.Headers(headers, encoding="utf-8") super().__init__(f"HTTP {status}: {message}") + def __reduce__(self): + # Pickle (worker pools, multiprocessing) rebuilds an exception from + # its args, which hold only the formatted text. + return ( + type(self), + (self.status, self.message, self.body, self.headers.multi_items()), + ) + class AuthenticationError(APIError): """Raised when authentication fails (401).""" @@ -117,3 +125,6 @@ def __init__(self, dependency: str, install_command: str): f"Missing required dependency: {dependency}\n" f"Install it with: {install_command}" ) + + def __reduce__(self): + return (type(self), (self.dependency, self.install_command)) diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index 785a86f..486bb6c 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -5,6 +5,7 @@ """ import contextlib +import pickle import threading from http.server import BaseHTTPRequestHandler, HTTPServer @@ -179,3 +180,30 @@ def test_an_error_whose_body_is_not_an_object_carries_the_headers(body): with pytest.raises(APIError) as caught: _raise_for_status(response) assert caught.value.headers["x-fish-trace-id"] == "trace-123" + + +@pytest.mark.parametrize("error_class", [APIError, AuthenticationError, RateLimitError]) +def test_error_survives_pickle(error_class): + """Errors cross process boundaries (worker pools) intact.""" + error = error_class( + 429, + "Too Many Requests", + body='{"detail": "slow down"}', + headers=[("x-fish-trace-id", "t"), ("set-cookie", "a"), ("set-cookie", "b")], + ) + copy = pickle.loads(pickle.dumps(error)) + assert type(copy) is error_class + assert (copy.status, copy.message, copy.body) == ( + error.status, + error.message, + error.body, + ) + assert copy.headers.multi_items() == error.headers.multi_items() + assert str(copy) == str(error) + + +def test_dependency_error_survives_pickle(): + from fishaudio.exceptions import DependencyError + + copy = pickle.loads(pickle.dumps(DependencyError("sounddevice", "pip install x"))) + assert (copy.dependency, copy.install_command) == ("sounddevice", "pip install x") From fd0864cf3d923d85cc331eda7d4e065e430af93f Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:55:12 -0800 Subject: [PATCH 04/13] fix(errors): pickle API errors with their headers as they are The reducer rebuilt headers from text, which re-encoded raw bytes (0xFF became C3 BF), and dropped state a caller attached, such as exception notes. The httpx Headers object and the instance's __dict__ now go through pickle unchanged. --- src/fishaudio/exceptions.py | 11 +++++------ tests/unit/test_error_headers.py | 12 ++++++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index 05c2f44..d130a7e1 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -40,11 +40,10 @@ def __init__( def __reduce__(self): # Pickle (worker pools, multiprocessing) rebuilds an exception from - # its args, which hold only the formatted text. - return ( - type(self), - (self.status, self.message, self.body, self.headers.multi_items()), - ) + # its args, which hold only the formatted text. The headers go as + # they are (raw bytes kept); __dict__ carries the rest (notes too). + args = (self.status, self.message, self.body, self.headers) + return (type(self), args, self.__dict__) class AuthenticationError(APIError): @@ -127,4 +126,4 @@ def __init__(self, dependency: str, install_command: str): ) def __reduce__(self): - return (type(self), (self.dependency, self.install_command)) + return (type(self), (self.dependency, self.install_command), self.__dict__) diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index 486bb6c..91a3eb5 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -207,3 +207,15 @@ def test_dependency_error_survives_pickle(): copy = pickle.loads(pickle.dumps(DependencyError("sounddevice", "pip install x"))) assert (copy.dependency, copy.install_command) == ("sounddevice", "pip install x") + + +def test_error_pickle_keeps_raw_header_bytes_and_extra_state(): + headers = httpx.Headers([(b"x-raw", b"\xff"), (b"x-fish-trace-id", b"t")]) + error = AuthenticationError(401, "Unauthorized", headers=headers) + error.job = "job 42" # extra state a caller attached, as add_note does + copy = pickle.loads(pickle.dumps(error)) + assert copy.headers.raw == error.headers.raw + assert copy.job == "job 42" + if hasattr(error, "add_note"): # Python 3.11+ + error.add_note("job 42") + assert pickle.loads(pickle.dumps(error)).__notes__ == ["job 42"] From 9edccbc3181b8a3971f42941f4438102e2c7d082 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:51:03 -0800 Subject: [PATCH 05/13] docs(asr): say how a request without a model moves off transcribe-1 --- src/fishaudio/resources/asr.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 0c6a86a..264bf77 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -109,7 +109,9 @@ def transcribe( transcribe-1 is deprecated and will be retired on December 31, 2026; after that date, the requests it serves, including those with no ``model`` header, are served by transcribe-2-pro. - Passing "transcribe-1" emits a FutureWarning. + Pass model="transcribe-2-pro" to move to it now; a request + without a model gets no warning. Passing "transcribe-1" + emits a FutureWarning. request_options: Request-level overrides Returns: @@ -306,7 +308,9 @@ async def transcribe( transcribe-1 is deprecated and will be retired on December 31, 2026; after that date, the requests it serves, including those with no ``model`` header, are served by transcribe-2-pro. - Passing "transcribe-1" emits a FutureWarning. + Pass model="transcribe-2-pro" to move to it now; a request + without a model gets no warning. Passing "transcribe-1" + emits a FutureWarning. request_options: Request-level overrides Returns: From 77530070ad1ea132cca0301ed6c9e4b065a88a7b Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:01:18 -0800 Subject: [PATCH 06/13] fix(errors): unpickle SDK errors without calling their constructor Pickling rebuilt APIError and DependencyError by calling the class with the base constructor's arguments, so a caller's subclass with another __init__ failed to unpickle, and a worker pool that sent one back broke. Every SDK error now pickles one way: the class and its args, restored without calling the constructor, then its attributes as they are (raw header bytes, notes and caller state kept). --- src/fishaudio/exceptions.py | 28 +++++++++------ tests/unit/test_error_headers.py | 60 ++++++++++++++++++++++++++++++-- 2 files changed, 75 insertions(+), 13 deletions(-) diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index d130a7e1..d6dc2be 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -1,14 +1,30 @@ """Custom exceptions for the Fish Audio SDK.""" from collections.abc import Mapping -from typing import Optional +from typing import Any, Optional import httpx +def _restore(cls: "type[FishAudioError]", args: tuple) -> "FishAudioError": + """Unpickle an SDK error without calling its constructor, which a + subclass may have changed; pickle then sets its attributes.""" + error = cls.__new__(cls) + error.args = args + return error + + class FishAudioError(Exception): """Base exception for all Fish Audio SDK errors.""" + def __reduce__(self) -> Any: + # Pickle (worker pools, multiprocessing) rebuilds an exception from + # its args by calling the class; SDK errors take other constructor + # arguments, and a caller's subclass may take others again. So: the + # class and its args without calling it, then every attribute as it + # is (raw header bytes, notes and state a caller added included). + return (_restore, (type(self), self.args), self.__dict__) + class APIError(FishAudioError): """Raised when the API returns an error response. @@ -38,13 +54,6 @@ def __init__( self.headers = httpx.Headers(headers, encoding="utf-8") super().__init__(f"HTTP {status}: {message}") - def __reduce__(self): - # Pickle (worker pools, multiprocessing) rebuilds an exception from - # its args, which hold only the formatted text. The headers go as - # they are (raw bytes kept); __dict__ carries the rest (notes too). - args = (self.status, self.message, self.body, self.headers) - return (type(self), args, self.__dict__) - class AuthenticationError(APIError): """Raised when authentication fails (401).""" @@ -124,6 +133,3 @@ def __init__(self, dependency: str, install_command: str): f"Missing required dependency: {dependency}\n" f"Install it with: {install_command}" ) - - def __reduce__(self): - return (type(self), (self.dependency, self.install_command), self.__dict__) diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index 91a3eb5..d3cb228 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -16,6 +16,7 @@ from fishaudio import APIError, AsyncFishAudio, AuthenticationError, FishAudio from fishaudio.core.client_wrapper import _raise_for_status from fishaudio.exceptions import ( + DependencyError, NotFoundError, PermissionError, RateLimitError, @@ -203,8 +204,6 @@ def test_error_survives_pickle(error_class): def test_dependency_error_survives_pickle(): - from fishaudio.exceptions import DependencyError - copy = pickle.loads(pickle.dumps(DependencyError("sounddevice", "pip install x"))) assert (copy.dependency, copy.install_command) == ("sounddevice", "pip install x") @@ -219,3 +218,60 @@ def test_error_pickle_keeps_raw_header_bytes_and_extra_state(): if hasattr(error, "add_note"): # Python 3.11+ error.add_note("job 42") assert pickle.loads(pickle.dumps(error)).__notes__ == ["job 42"] + + +class _QuotaError(APIError): + """A caller's subclass with a constructor of its own.""" + + def __init__(self, job): + super().__init__(429, f"quota for {job}") + self.job = job + + +class _ToolMissing(DependencyError): + def __init__(self): + super().__init__("mytool", "pip install mytool") + + +def _fail_with_quota_error(job): + raise _QuotaError(job) + + +def _double(value): + return value * 2 + + +@pytest.mark.parametrize("make", [lambda: _QuotaError("job 7"), _ToolMissing]) +def test_a_subclass_with_its_own_constructor_survives_pickle(make): + error = make() + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + copy = pickle.loads(pickle.dumps(error, protocol)) + assert type(copy) is type(error) + assert copy.__dict__.keys() == error.__dict__.keys() + assert str(copy) == str(error) + + +def test_a_worker_pool_delivers_a_subclass_error_and_takes_the_next_job(): + from concurrent.futures import ProcessPoolExecutor + + with ProcessPoolExecutor(max_workers=1) as pool: + with pytest.raises(_QuotaError) as caught: + pool.submit(_fail_with_quota_error, "job 7").result(timeout=60) + assert (caught.value.job, caught.value.status) == ("job 7", 429) + assert pool.submit(_double, 21).result(timeout=60) == 42 + + +def test_a_structured_message_becomes_text_and_the_body_keeps_it(): + import json + + detail = [{"loc": ["body", "text"], "msg": "field required"}] + response = httpx.Response( + 422, + json={"detail": detail}, + request=httpx.Request("POST", "https://api.fish.audio/v1/tts"), + ) + with pytest.raises(APIError) as caught: + _raise_for_status(response) + assert isinstance(caught.value.message, str) + assert json.loads(caught.value.message) == detail + assert json.loads(caught.value.body)["detail"] == detail From 887428ef5f140c81b00ee06cbade918e168a25ee Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:01:18 -0800 Subject: [PATCH 07/13] fix(errors): APIError.message is text when the API sends a structured field A 422 whose detail is a list put the list in message, which is typed str. The field is now turned into JSON text; body keeps the response as sent. --- src/fishaudio/core/client_wrapper.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index e18c1df..637ef3b 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -1,5 +1,6 @@ """HTTP client wrapper for managing requests and authentication.""" +import json import os import platform import re @@ -74,6 +75,7 @@ def _raise_for_status(response: httpx.Response) -> None: If the body is a JSON object with a truthy ``message`` field, that is the message; otherwise its truthy ``detail`` field. In every other case the message is the body text, or the status phrase when the text is empty. + A field that is not a string is turned into JSON text. """ status = response.status_code data, text = _read_error_body(response) @@ -81,6 +83,13 @@ def _raise_for_status(response: httpx.Response) -> None: message = None if isinstance(data, dict): message = data.get("message") or data.get("detail") + if message and not isinstance(message, str): + # A structured field (a 422's list of problems, say) becomes text: + # APIError.message is a str. The body keeps the content as sent. + try: + message = json.dumps(message, ensure_ascii=False) + except (TypeError, ValueError): + message = str(message) raise _api_error( status, From 179157106ad9e27c696092fbbc07421732919a28 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:01:18 -0800 Subject: [PATCH 08/13] fix(utils): stream() takes any iterable of audio chunks It only loops over them, so stream(client.tts.stream(...)) is accepted by a type checker too. The docstring example now passes a stream, not convert()'s bytes. --- src/fishaudio/utils/stream.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/fishaudio/utils/stream.py b/src/fishaudio/utils/stream.py index 3e50537..4e11754 100644 --- a/src/fishaudio/utils/stream.py +++ b/src/fishaudio/utils/stream.py @@ -2,7 +2,7 @@ import shutil import subprocess -from collections.abc import Iterator +from collections.abc import Iterable from fishaudio.exceptions import DependencyError @@ -12,7 +12,7 @@ def _is_installed(command: str) -> bool: return shutil.which(command) is not None -def stream(audio_stream: Iterator[bytes]) -> bytes: +def stream(audio_stream: Iterable[bytes]) -> bytes: """ Stream audio in real-time while playing it with mpv. @@ -20,7 +20,7 @@ def stream(audio_stream: Iterator[bytes]) -> bytes: simultaneously captures it to return the complete audio buffer. Args: - audio_stream: Iterator of audio byte chunks + audio_stream: Audio byte chunks, such as ``client.tts.stream(...)`` Returns: Complete audio bytes after streaming finishes @@ -33,7 +33,7 @@ def stream(audio_stream: Iterator[bytes]) -> bytes: from fishaudio import FishAudio, stream client = FishAudio(api_key="...") - audio_stream = client.tts.convert(text="Hello world") + audio_stream = client.tts.stream(text="Hello world") # Stream and play in real-time, get complete audio complete_audio = stream(audio_stream) From 1d375d93ca7524e3399b36e2481deddd788799b3 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:01:18 -0800 Subject: [PATCH 09/13] docs: say exactly when play() falls back and which transcribe-1 models warn --- src/fishaudio/resources/asr.py | 12 ++++++++---- src/fishaudio/utils/play.py | 13 +++++++++---- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 264bf77..b2299c9 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -110,8 +110,10 @@ def transcribe( 2026; after that date, the requests it serves, including those with no ``model`` header, are served by transcribe-2-pro. Pass model="transcribe-2-pro" to move to it now; a request - without a model gets no warning. Passing "transcribe-1" - emits a FutureWarning. + without a model gets no warning. "transcribe-1" given as + ``model`` or as a ``model`` header in request_options emits + a FutureWarning; one set only in a custom httpx client's + headers is not seen. request_options: Request-level overrides Returns: @@ -309,8 +311,10 @@ async def transcribe( 2026; after that date, the requests it serves, including those with no ``model`` header, are served by transcribe-2-pro. Pass model="transcribe-2-pro" to move to it now; a request - without a model gets no warning. Passing "transcribe-1" - emits a FutureWarning. + without a model gets no warning. "transcribe-1" given as + ``model`` or as a ``model`` header in request_options emits + a FutureWarning; one set only in a custom httpx client's + headers is not seen. request_options: Request-level overrides Returns: diff --git a/src/fishaudio/utils/play.py b/src/fishaudio/utils/play.py index 601836f..a4ac73b 100644 --- a/src/fishaudio/utils/play.py +++ b/src/fishaudio/utils/play.py @@ -27,12 +27,17 @@ def play( audio: Audio bytes or iterable of bytes notebook: Use Jupyter notebook playback (IPython.display.Audio) use_ffmpeg: Play with ffplay (the default). If ffplay is not - installed, DependencyError is raised; there is no fallback. If - ffplay is installed but fails, playback falls back to sounddevice. - False plays with sounddevice (the ``[utils]`` extra). + installed, DependencyError is raised; there is no fallback. + Playback falls back to sounddevice only when ffplay exits with a + non-zero status (an ffplay that reports a problem but exits with + 0 counts as played). False plays with sounddevice (the + ``[utils]`` extra). Raises: - DependencyError: If the playback tool to use is not installed + DependencyError: If ffplay is not installed (``use_ffmpeg=True``), or + the sounddevice or soundfile package is not installed when + sounddevice is used. Other errors importing them, such as a + missing PortAudio library, are raised as they are. Examples: ```python From 65da0b97683185073f99fc090b30686ea1bf60d5 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:09:32 -0800 Subject: [PATCH 10/13] fix(errors): change pickling only for the SDK's own error construction The reducer on FishAudioError restored every subclass with cls.__new__(cls) and only its __dict__, so a caller's subclass whose __new__ needs an argument broke a worker pool, and one with __slots__ lost its fields. APIError and DependencyError now pass their own constructor arguments only when the class is constructed as theirs is (same __init__ and __new__); any other subclass pickles exactly as on 1.8.1. --- src/fishaudio/exceptions.py | 37 ++++++++----- tests/unit/test_error_headers.py | 95 +++++++++++++++++++++++++++----- 2 files changed, 104 insertions(+), 28 deletions(-) diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index d6dc2be..61a7fb0 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -6,25 +6,16 @@ import httpx -def _restore(cls: "type[FishAudioError]", args: tuple) -> "FishAudioError": - """Unpickle an SDK error without calling its constructor, which a - subclass may have changed; pickle then sets its attributes.""" - error = cls.__new__(cls) - error.args = args - return error +def _builds_as(error: BaseException, cls: type) -> bool: + """Whether error's class is constructed exactly as cls is (the SDK's own + construction), not by a subclass that changed __init__ or __new__.""" + kind = type(error) + return kind.__init__ is cls.__init__ and kind.__new__ is cls.__new__ class FishAudioError(Exception): """Base exception for all Fish Audio SDK errors.""" - def __reduce__(self) -> Any: - # Pickle (worker pools, multiprocessing) rebuilds an exception from - # its args by calling the class; SDK errors take other constructor - # arguments, and a caller's subclass may take others again. So: the - # class and its args without calling it, then every attribute as it - # is (raw header bytes, notes and state a caller added included). - return (_restore, (type(self), self.args), self.__dict__) - class APIError(FishAudioError): """Raised when the API returns an error response. @@ -54,6 +45,17 @@ def __init__( self.headers = httpx.Headers(headers, encoding="utf-8") super().__init__(f"HTTP {status}: {message}") + def __reduce__(self) -> Any: + # Pickle (worker pools, multiprocessing) calls the class with args, + # which hold only the formatted text. For the SDK's own construction, + # pass the constructor's arguments instead (the headers as they are, + # raw bytes kept); __dict__ carries the rest. A subclass that changes + # construction pickles as any exception does. + if _builds_as(self, APIError): + args = (self.status, self.message, self.body, self.headers) + return (type(self), args, self.__dict__) + return super().__reduce__() + class AuthenticationError(APIError): """Raised when authentication fails (401).""" @@ -133,3 +135,10 @@ def __init__(self, dependency: str, install_command: str): f"Missing required dependency: {dependency}\n" f"Install it with: {install_command}" ) + + def __reduce__(self) -> Any: + # As APIError.__reduce__: the SDK's own construction only. + if _builds_as(self, DependencyError): + args = (self.dependency, self.install_command) + return (type(self), args, self.__dict__) + return super().__reduce__() diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index d3cb228..1a5705c 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -220,47 +220,114 @@ def test_error_pickle_keeps_raw_header_bytes_and_extra_state(): assert pickle.loads(pickle.dumps(error)).__notes__ == ["job 42"] +# A caller's subclasses that change construction pickle exactly as any +# exception does (as on 1.8.1): these tests pass on origin/main too. + + class _QuotaError(APIError): - """A caller's subclass with a constructor of its own.""" + """One constructor argument, kept in args.""" def __init__(self, job): super().__init__(429, f"quota for {job}") + self.args = (job,) + self.job = job + + +class _JobError(APIError): + """A __new__ that needs its argument.""" + + def __new__(cls, job): + return super().__new__(cls, job) + + def __init__(self, job): + super().__init__(500, f"job {job} failed") + self.args = (job,) + self.job = job + + +class _SlotError(APIError): + """A field kept in a slot, set in __init__.""" + + __slots__ = ("job",) + + def __init__(self, job): + super().__init__(400, f"job {job} rejected") + self.args = (job,) self.job = job class _ToolMissing(DependencyError): - def __init__(self): - super().__init__("mytool", "pip install mytool") + def __init__(self, tool): + super().__init__(tool, f"pip install {tool}") + self.args = (tool,) -def _fail_with_quota_error(job): - raise _QuotaError(job) +def _raise(kind, job): + raise kind(job) def _double(value): return value * 2 -@pytest.mark.parametrize("make", [lambda: _QuotaError("job 7"), _ToolMissing]) -def test_a_subclass_with_its_own_constructor_survives_pickle(make): - error = make() +@pytest.mark.parametrize("kind", [_QuotaError, _JobError, _SlotError, _ToolMissing]) +def test_a_subclass_that_changes_construction_pickles_as_any_exception(kind): + error = kind("job 7") for protocol in range(pickle.HIGHEST_PROTOCOL + 1): copy = pickle.loads(pickle.dumps(error, protocol)) - assert type(copy) is type(error) - assert copy.__dict__.keys() == error.__dict__.keys() + assert type(copy) is kind + assert copy.args == error.args assert str(copy) == str(error) + if kind is not _ToolMissing: + assert (copy.job, copy.status, copy.message) == ( + error.job, + error.status, + error.message, + ) -def test_a_worker_pool_delivers_a_subclass_error_and_takes_the_next_job(): +@pytest.mark.parametrize("kind", [_QuotaError, _JobError]) +def test_a_worker_pool_delivers_a_subclass_error_and_takes_the_next_job(kind): from concurrent.futures import ProcessPoolExecutor with ProcessPoolExecutor(max_workers=1) as pool: - with pytest.raises(_QuotaError) as caught: - pool.submit(_fail_with_quota_error, "job 7").result(timeout=60) - assert (caught.value.job, caught.value.status) == ("job 7", 429) + with pytest.raises(kind) as caught: + pool.submit(_raise, kind, "job 7").result(timeout=60) + assert caught.value.job == "job 7" assert pool.submit(_double, 21).result(timeout=60) == 42 +def test_a_worker_pool_delivers_the_sdks_own_error_and_takes_the_next_job(): + from concurrent.futures import ProcessPoolExecutor + + with ProcessPoolExecutor(max_workers=1) as pool: + with pytest.raises(RateLimitError) as caught: + pool.submit(_raise_rate_limit).result(timeout=60) + assert caught.value.headers.multi_items() == [ + ("set-cookie", "a"), + ("set-cookie", "b"), + ] + assert pool.submit(_double, 21).result(timeout=60) == 42 + + +def _raise_rate_limit(): + raise RateLimitError( + 429, "Too Many Requests", headers=[("set-cookie", "a"), ("set-cookie", "b")] + ) + + +def test_realtime_asr_error_survives_pickle(): + from fishaudio.exceptions import ASRRealtimeError + + error = ASRRealtimeError( + "bad config", error_type="invalid_config", request_id="req", close_code=4400 + ) + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + copy = pickle.loads(pickle.dumps(error, protocol)) + assert copy.__dict__ == error.__dict__ + assert copy.args == error.args + + def test_a_structured_message_becomes_text_and_the_body_keeps_it(): import json From 1bf830589866ca7f1f5fec23d25749fb2b5a47bf Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:09:32 -0800 Subject: [PATCH 11/13] docs: when transcribe-1 is the default, closing stream() responses, play() import errors --- src/fishaudio/resources/asr.py | 10 ++++++---- src/fishaudio/utils/play.py | 9 ++++++--- src/fishaudio/utils/stream.py | 7 ++++--- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index b2299c9..88749e2 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -104,8 +104,9 @@ def transcribe( (and speaker turns, on models that return them) model: ASR model, e.g. "transcribe-2-pro" (recommended). Sent as the ``model`` header and takes precedence over one in request_options. - If not provided and request_options sets no ``model`` header, the - request runs on the API's default model, transcribe-1. + When the outgoing request carries no ``model`` header (from + this argument, request_options, or headers set on a custom + httpx client), it runs on the API's default model, transcribe-1. transcribe-1 is deprecated and will be retired on December 31, 2026; after that date, the requests it serves, including those with no ``model`` header, are served by transcribe-2-pro. @@ -305,8 +306,9 @@ async def transcribe( (and speaker turns, on models that return them) model: ASR model, e.g. "transcribe-2-pro" (recommended). Sent as the ``model`` header and takes precedence over one in request_options. - If not provided and request_options sets no ``model`` header, the - request runs on the API's default model, transcribe-1. + When the outgoing request carries no ``model`` header (from + this argument, request_options, or headers set on a custom + httpx client), it runs on the API's default model, transcribe-1. transcribe-1 is deprecated and will be retired on December 31, 2026; after that date, the requests it serves, including those with no ``model`` header, are served by transcribe-2-pro. diff --git a/src/fishaudio/utils/play.py b/src/fishaudio/utils/play.py index a4ac73b..93a0d40 100644 --- a/src/fishaudio/utils/play.py +++ b/src/fishaudio/utils/play.py @@ -35,9 +35,12 @@ def play( Raises: DependencyError: If ffplay is not installed (``use_ffmpeg=True``), or - the sounddevice or soundfile package is not installed when - sounddevice is used. Other errors importing them, such as a - missing PortAudio library, are raised as they are. + sounddevice or soundfile cannot be imported when sounddevice is + used: any ImportError from importing them (a missing package, or + a missing native binding) is raised as DependencyError, with the + original error chained to it. Other errors from importing them + (an OSError for a missing PortAudio library, say) are raised as + they are. Examples: ```python diff --git a/src/fishaudio/utils/stream.py b/src/fishaudio/utils/stream.py index 4e11754..1e64d53 100644 --- a/src/fishaudio/utils/stream.py +++ b/src/fishaudio/utils/stream.py @@ -33,10 +33,11 @@ def stream(audio_stream: Iterable[bytes]) -> bytes: from fishaudio import FishAudio, stream client = FishAudio(api_key="...") - audio_stream = client.tts.stream(text="Hello world") - # Stream and play in real-time, get complete audio - complete_audio = stream(audio_stream) + # Stream and play in real-time, get complete audio. The with block + # closes the response even if playback fails (mpv missing, say). + with client.tts.stream(text="Hello world") as audio_stream: + complete_audio = stream(audio_stream) # Save the captured audio with open("output.mp3", "wb") as f: From 2631ed92a153396879cbd590eb24376b3caa85cc Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:20:16 -0800 Subject: [PATCH 12/13] fix(errors): a metaclass that constructs the error also keeps main's pickling The check for the SDK's own construction looked at __init__ and __new__ only. A subclass whose metaclass constructs it now pickles as any exception does, as on main. play() docs name the notebook case. --- src/fishaudio/exceptions.py | 9 +++++++-- src/fishaudio/utils/play.py | 3 ++- tests/unit/test_error_headers.py | 21 +++++++++++++++++++-- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index 61a7fb0..d4281e8 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -8,9 +8,14 @@ def _builds_as(error: BaseException, cls: type) -> bool: """Whether error's class is constructed exactly as cls is (the SDK's own - construction), not by a subclass that changed __init__ or __new__.""" + construction), not by a subclass that changed __init__ or __new__, or + whose metaclass does the constructing.""" kind = type(error) - return kind.__init__ is cls.__init__ and kind.__new__ is cls.__new__ + return ( + type(kind) is type(cls) + and kind.__init__ is cls.__init__ + and kind.__new__ is cls.__new__ + ) class FishAudioError(Exception): diff --git a/src/fishaudio/utils/play.py b/src/fishaudio/utils/play.py index 93a0d40..d67bcec 100644 --- a/src/fishaudio/utils/play.py +++ b/src/fishaudio/utils/play.py @@ -34,7 +34,8 @@ def play( ``[utils]`` extra). Raises: - DependencyError: If ffplay is not installed (``use_ffmpeg=True``), or + DependencyError: If IPython is not installed (``notebook=True``, which + is checked first), if ffplay is not installed (``use_ffmpeg=True``), or sounddevice or soundfile cannot be imported when sounddevice is used: any ImportError from importing them (a missing package, or a missing native binding) is raised as DependencyError, with the diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index 1a5705c..c394eb0 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -256,6 +256,21 @@ def __init__(self, job): self.job = job +class _OneArgument(type): + """A metaclass that constructs the error from one argument.""" + + def __call__(cls, job): + error = cls.__new__(cls) + APIError.__init__(error, 409, f"job {job} conflicts") + error.args = (job,) + error.job = job + return error + + +class _MetaError(APIError, metaclass=_OneArgument): + """__init__ and __new__ are the SDK's; the metaclass constructs.""" + + class _ToolMissing(DependencyError): def __init__(self, tool): super().__init__(tool, f"pip install {tool}") @@ -270,7 +285,9 @@ def _double(value): return value * 2 -@pytest.mark.parametrize("kind", [_QuotaError, _JobError, _SlotError, _ToolMissing]) +@pytest.mark.parametrize( + "kind", [_QuotaError, _JobError, _SlotError, _MetaError, _ToolMissing] +) def test_a_subclass_that_changes_construction_pickles_as_any_exception(kind): error = kind("job 7") for protocol in range(pickle.HIGHEST_PROTOCOL + 1): @@ -286,7 +303,7 @@ def test_a_subclass_that_changes_construction_pickles_as_any_exception(kind): ) -@pytest.mark.parametrize("kind", [_QuotaError, _JobError]) +@pytest.mark.parametrize("kind", [_QuotaError, _JobError, _MetaError]) def test_a_worker_pool_delivers_a_subclass_error_and_takes_the_next_job(kind): from concurrent.futures import ProcessPoolExecutor From f2780376c6c44cc43922200ec43de1038c8b377f Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:26:56 -0800 Subject: [PATCH 13/13] docs: say when a request_options model warns and that notebook mode ignores use_ffmpeg Also drop the fallback around json.dumps for a structured error message: the value comes from parsed JSON, so it always serializes. --- src/fishaudio/core/client_wrapper.py | 5 +---- src/fishaudio/resources/asr.py | 12 ++++++------ src/fishaudio/utils/play.py | 6 ++++-- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 637ef3b..dcd4290 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -86,10 +86,7 @@ def _raise_for_status(response: httpx.Response) -> None: if message and not isinstance(message, str): # A structured field (a 422's list of problems, say) becomes text: # APIError.message is a str. The body keeps the content as sent. - try: - message = json.dumps(message, ensure_ascii=False) - except (TypeError, ValueError): - message = str(message) + message = json.dumps(message, ensure_ascii=False) raise _api_error( status, diff --git a/src/fishaudio/resources/asr.py b/src/fishaudio/resources/asr.py index 88749e2..3699273 100644 --- a/src/fishaudio/resources/asr.py +++ b/src/fishaudio/resources/asr.py @@ -112,9 +112,9 @@ def transcribe( with no ``model`` header, are served by transcribe-2-pro. Pass model="transcribe-2-pro" to move to it now; a request without a model gets no warning. "transcribe-1" given as - ``model`` or as a ``model`` header in request_options emits - a FutureWarning; one set only in a custom httpx client's - headers is not seen. + ``model``, or as a ``model`` header in request_options when + ``model`` is not given, emits a FutureWarning; one set only + in a custom httpx client's headers is not seen. request_options: Request-level overrides Returns: @@ -314,9 +314,9 @@ async def transcribe( with no ``model`` header, are served by transcribe-2-pro. Pass model="transcribe-2-pro" to move to it now; a request without a model gets no warning. "transcribe-1" given as - ``model`` or as a ``model`` header in request_options emits - a FutureWarning; one set only in a custom httpx client's - headers is not seen. + ``model``, or as a ``model`` header in request_options when + ``model`` is not given, emits a FutureWarning; one set only + in a custom httpx client's headers is not seen. request_options: Request-level overrides Returns: diff --git a/src/fishaudio/utils/play.py b/src/fishaudio/utils/play.py index d67bcec..199c652 100644 --- a/src/fishaudio/utils/play.py +++ b/src/fishaudio/utils/play.py @@ -25,8 +25,10 @@ def play( Args: audio: Audio bytes or iterable of bytes - notebook: Use Jupyter notebook playback (IPython.display.Audio) - use_ffmpeg: Play with ffplay (the default). If ffplay is not + notebook: Use Jupyter notebook playback (IPython.display.Audio). + ``use_ffmpeg`` is then ignored: neither ffplay nor sounddevice + is used. + use_ffmpeg: Outside notebook mode, play with ffplay (the default). If ffplay is not installed, DependencyError is raised; there is no fallback. Playback falls back to sounddevice only when ffplay exits with a non-zero status (an ffplay that reports a problem but exits with