From 90ca64d03e0f377deba5ffb649b0ef80b952eba9 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:10:30 -0800 Subject: [PATCH 1/2] fix(tts): stream HTTP audio incrementally instead of buffering the full response tts.stream() went through ClientWrapper.request(), which calls httpx.Client.request(). That reads the whole response body before returning, so iter_bytes() only replayed data already in memory: callers got one chunk after the full generation finished. Add a stream=True mode to ClientWrapper/AsyncClientWrapper.request() that uses build_request() + send(stream=True), reads the body only on error so exceptions keep their message, and close the response when the generator finishes or is abandoned. Use it in TTSClient.stream() and AsyncTTSClient.stream(). convert() is unchanged (stream().collect()). Add tests that run through a real httpx MockTransport and assert the first chunk is yielded before the rest of the body is read. Co-Authored-By: Claude Opus 5.5 --- src/fishaudio/core/client_wrapper.py | 36 ++++++ src/fishaudio/resources/tts.py | 26 +++-- tests/unit/test_streaming.py | 158 +++++++++++++++++++++++++++ tests/unit/test_tts.py | 16 +++ 4 files changed, 228 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_streaming.py diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index 4164ba2..a4a5a48 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -122,6 +122,7 @@ def request( path: str, *, request_options: Optional[RequestOptions] = None, + stream: bool = False, **kwargs: Any, ) -> httpx.Response: """ @@ -131,6 +132,9 @@ def request( method: HTTP method (GET, POST, etc.) path: API endpoint path request_options: Optional request-level overrides + stream: If True, return as soon as the response headers arrive and + leave the body unread. The caller must consume it with + `iter_bytes()` and then call `close()` on the response. **kwargs: Additional arguments to pass to httpx.request Returns: @@ -141,6 +145,20 @@ def request( """ self._prepare_request_kwargs(request_options, kwargs) + if stream: + timeout = kwargs.pop("timeout", httpx.USE_CLIENT_DEFAULT) + http_request = self._client.build_request( + method, path, timeout=timeout, **kwargs + ) + response = self._client.send(http_request, stream=True) + if not response.is_success: + try: + response.read() + finally: + response.close() + _raise_for_status(response) + return response + # Make the request response = self._client.request(method, path, **kwargs) @@ -194,6 +212,7 @@ async def request( path: str, *, request_options: Optional[RequestOptions] = None, + stream: bool = False, **kwargs: Any, ) -> httpx.Response: """ @@ -203,6 +222,9 @@ async def request( method: HTTP method (GET, POST, etc.) path: API endpoint path request_options: Optional request-level overrides + stream: If True, return as soon as the response headers arrive and + leave the body unread. The caller must consume it with + `aiter_bytes()` and then call `aclose()` on the response. **kwargs: Additional arguments to pass to httpx.request Returns: @@ -213,6 +235,20 @@ async def request( """ self._prepare_request_kwargs(request_options, kwargs) + if stream: + timeout = kwargs.pop("timeout", httpx.USE_CLIENT_DEFAULT) + http_request = self._client.build_request( + method, path, timeout=timeout, **kwargs + ) + response = await self._client.send(http_request, stream=True) + if not response.is_success: + try: + await response.aread() + finally: + await response.aclose() + _raise_for_status(response) + return response + # Make the request response = await self._client.request(method, path, **kwargs) diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 62307a4..9bc477d 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -140,20 +140,25 @@ def stream( payload = request.model_dump(exclude_none=True) - # Make request with streaming + # Send the request and return once headers arrive; the body is read + # lazily so chunks reach the caller as the server produces them. response = self._client.request( "POST", "/v1/tts", headers={"Content-Type": "application/msgpack", "model": model}, content=ormsgpack.packb(payload), request_options=request_options, + stream=True, ) # Create generator and wrap with AudioStream def _stream(): - for chunk in response.iter_bytes(): - if chunk: - yield chunk + try: + for chunk in response.iter_bytes(): + if chunk: + yield chunk + finally: + response.close() return AudioStream(_stream()) @@ -450,20 +455,25 @@ async def stream( payload = request.model_dump(exclude_none=True) - # Make request with streaming + # Send the request and return once headers arrive; the body is read + # lazily so chunks reach the caller as the server produces them. response = await self._client.request( "POST", "/v1/tts", headers={"Content-Type": "application/msgpack", "model": model}, content=ormsgpack.packb(payload), request_options=request_options, + stream=True, ) # Create async generator and wrap with AsyncAudioStream async def _stream(): - async for chunk in response.aiter_bytes(): - if chunk: - yield chunk + try: + async for chunk in response.aiter_bytes(): + if chunk: + yield chunk + finally: + await response.aclose() return AsyncAudioStream(_stream()) diff --git a/tests/unit/test_streaming.py b/tests/unit/test_streaming.py new file mode 100644 index 0000000..ba82d94 --- /dev/null +++ b/tests/unit/test_streaming.py @@ -0,0 +1,158 @@ +"""Tests that TTS streaming delivers chunks incrementally over real httpx transports. + +These use httpx.MockTransport instead of mocking ClientWrapper.request, so they +exercise the actual request/response path and would catch the SDK buffering the +whole response body before yielding. +""" + +import httpx +import pytest + +from fishaudio.core import AsyncClientWrapper, ClientWrapper +from fishaudio.exceptions import APIError, RateLimitError +from fishaudio.resources.tts import AsyncTTSClient, TTSClient + +BASE_URL = "https://api.test.fish.audio" +CHUNKS = [b"chunk-1", b"chunk-2", b"chunk-3"] + + +class _SyncBody(httpx.SyncByteStream): + """Response body that records how far the server has been read.""" + + def __init__(self, chunks): + self.chunks = chunks + self.produced = 0 + self.closed = False + + def __iter__(self): + for chunk in self.chunks: + self.produced += 1 + yield chunk + + def close(self): + self.closed = True + + +class _AsyncBody(httpx.AsyncByteStream): + def __init__(self, chunks): + self.chunks = chunks + self.produced = 0 + self.closed = False + + async def __aiter__(self): + for chunk in self.chunks: + self.produced += 1 + yield chunk + + async def aclose(self): + self.closed = True + + +def _sync_tts(handler): + http = httpx.Client(base_url=BASE_URL, transport=httpx.MockTransport(handler)) + return TTSClient(ClientWrapper(api_key="test", httpx_client=http)) + + +def _async_tts(handler): + http = httpx.AsyncClient(base_url=BASE_URL, transport=httpx.MockTransport(handler)) + return AsyncTTSClient(AsyncClientWrapper(api_key="test", httpx_client=http)) + + +class TestSyncStreaming: + def test_first_chunk_arrives_before_body_is_read(self): + body = _SyncBody(CHUNKS) + tts = _sync_tts(lambda request: httpx.Response(200, stream=body)) + + stream = iter(tts.stream(text="Hello")) + assert body.produced == 0 # nothing read until the caller iterates + + assert next(stream) == b"chunk-1" + assert body.produced == 1 # the rest of the body is still unread + + assert list(stream) == [b"chunk-2", b"chunk-3"] + assert body.closed + + def test_early_break_closes_response(self): + body = _SyncBody(CHUNKS) + tts = _sync_tts(lambda request: httpx.Response(200, stream=body)) + + stream = tts.stream(text="Hello") + for _ in stream: + break + stream._iter.close() # what garbage collection does to an abandoned generator + + assert body.produced == 1 + assert body.closed + + def test_convert_still_returns_full_audio(self): + tts = _sync_tts(lambda request: httpx.Response(200, stream=_SyncBody(CHUNKS))) + assert tts.convert(text="Hello") == b"".join(CHUNKS) + + def test_error_raises_with_server_message(self): + tts = _sync_tts( + lambda request: httpx.Response(429, json={"message": "Too many requests"}) + ) + with pytest.raises(RateLimitError) as exc: + tts.stream(text="Hello") + assert exc.value.status == 429 + assert "Too many requests" in str(exc.value) + + def test_error_raised_at_call_time_not_on_iteration(self): + tts = _sync_tts(lambda request: httpx.Response(402, text="Insufficient credit")) + with pytest.raises(APIError) as exc: + tts.stream(text="Hello") + assert exc.value.status == 402 + + def test_request_options_timeout_applies(self): + seen = {} + + def handler(request): + seen["timeout"] = request.extensions["timeout"] + return httpx.Response(200, stream=_SyncBody(CHUNKS)) + + from fishaudio.core import RequestOptions + + tts = _sync_tts(handler) + tts.stream(text="Hello", request_options=RequestOptions(timeout=12.5)).collect() + assert seen["timeout"]["read"] == 12.5 + + +class TestAsyncStreaming: + async def test_first_chunk_arrives_before_body_is_read(self): + body = _AsyncBody(CHUNKS) + tts = _async_tts(lambda request: httpx.Response(200, stream=body)) + + stream = (await tts.stream(text="Hello")).__aiter__() + assert body.produced == 0 + + assert await stream.__anext__() == b"chunk-1" + assert body.produced == 1 + + rest = [chunk async for chunk in stream] + assert rest == [b"chunk-2", b"chunk-3"] + assert body.closed + + async def test_early_break_closes_response(self): + body = _AsyncBody(CHUNKS) + tts = _async_tts(lambda request: httpx.Response(200, stream=body)) + + stream = await tts.stream(text="Hello") + async for _ in stream: + break + await stream._iter.aclose() + + assert body.produced == 1 + assert body.closed + + async def test_convert_still_returns_full_audio(self): + tts = _async_tts(lambda request: httpx.Response(200, stream=_AsyncBody(CHUNKS))) + assert await tts.convert(text="Hello") == b"".join(CHUNKS) + + async def test_error_raises_with_server_message(self): + tts = _async_tts( + lambda request: httpx.Response(429, json={"message": "Too many requests"}) + ) + with pytest.raises(RateLimitError) as exc: + await tts.stream(text="Hello") + assert exc.value.status == 429 + assert "Too many requests" in str(exc.value) diff --git a/tests/unit/test_tts.py b/tests/unit/test_tts.py index 7cabc48..859d90d 100644 --- a/tests/unit/test_tts.py +++ b/tests/unit/test_tts.py @@ -520,6 +520,7 @@ async def async_iter_bytes(): yield chunk mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) # Call stream and collect chunks @@ -549,6 +550,7 @@ async def async_iter_bytes(): yield chunk mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) # Call convert @@ -574,6 +576,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) config = TTSConfig(reference_id="voice_123") @@ -595,6 +598,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) await async_tts_client.convert(text="Hello", reference_id="voice_456") @@ -615,6 +619,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) config = TTSConfig(reference_id="voice_from_config") @@ -638,6 +643,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) references = [ @@ -665,6 +671,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) config_refs = [ReferenceAudio(audio=b"config_audio", text="Config")] @@ -692,6 +699,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) prosody = Prosody(speed=2.0, volume=1.0) @@ -716,6 +724,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) await async_tts_client.convert(text="Hello") @@ -740,6 +749,7 @@ async def async_iter_bytes(): yield # Make it a generator mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) audio = await async_tts_client.convert(text="Hello") @@ -757,6 +767,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) await async_tts_client.convert(text="Hello", format="wav") @@ -777,6 +788,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) await async_tts_client.convert(text="Hello", latency="normal") @@ -797,6 +809,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) await async_tts_client.convert(text="Hello", speed=1.5) @@ -817,6 +830,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) config = TTSConfig(format="wav") @@ -838,6 +852,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) config = TTSConfig(prosody=Prosody(speed=2.0, volume=0.5)) @@ -860,6 +875,7 @@ async def async_iter_bytes(): yield b"audio" mock_response.aiter_bytes = async_iter_bytes + mock_response.aclose = AsyncMock() async_mock_client_wrapper.request = AsyncMock(return_value=mock_response) await async_tts_client.convert( From ef23521b6ad8b548075aa8e49114589fc26428b8 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:18:47 -0800 Subject: [PATCH 2/2] fix(tts): let audio streams release the HTTP response on close With incremental streaming, the response stayed open until the generator finished. A stream that was never iterated, or was left after an early break, kept its connection checked out of the pool. AudioStream and AsyncAudioStream now own the response: close()/aclose() release it whether or not iteration has started, both work as context managers, and collect() closes when done. Closing is idempotent. Co-Authored-By: Claude Opus 5.5 --- src/fishaudio/core/iterators.py | 105 ++++++++++++++++++++++++++++---- src/fishaudio/resources/tts.py | 4 +- tests/unit/test_streaming.py | 58 +++++++++++++++--- 3 files changed, 144 insertions(+), 23 deletions(-) diff --git a/src/fishaudio/core/iterators.py b/src/fishaudio/core/iterators.py index e82fcd7..4761848 100644 --- a/src/fishaudio/core/iterators.py +++ b/src/fishaudio/core/iterators.py @@ -1,6 +1,7 @@ """Audio stream wrappers with collection utilities.""" -from collections.abc import AsyncIterator, Iterator +from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from typing import Optional class AudioStream: @@ -21,21 +22,59 @@ class AudioStream: # Or stream chunks manually for chunk in client.tts.stream(text="Hello!"): process_chunk(chunk) + + # Use a with-block (or call close()) if you may stop early, + # so the HTTP connection is released right away + with client.tts.stream(text="Hello!") as stream: + for chunk in stream: + if done(chunk): + break ``` """ - def __init__(self, iterator: Iterator[bytes]): + def __init__( + self, + iterator: Iterator[bytes], + *, + on_close: Optional[Callable[[], None]] = None, + ): """Initialize the audio iterator wrapper. Args: iterator: The underlying iterator of audio bytes + on_close: Called by close() to release the underlying resource, + for example the open HTTP response """ self._iter = iterator + self._on_close = on_close + self._closed = False def __iter__(self) -> Iterator[bytes]: """Allow direct iteration over audio chunks.""" return self._iter + def close(self) -> None: + """Stop the stream and release the underlying connection. + + Safe to call more than once, and before iteration has started. + """ + if self._closed: + return + self._closed = True + try: + close_iter = getattr(self._iter, "close", None) + if close_iter is not None: + close_iter() + finally: + if self._on_close is not None: + self._on_close() + + def __enter__(self) -> "AudioStream": + return self + + def __exit__(self, exc_type, exc_val, exc_tb) -> None: + self.close() + def collect(self) -> bytes: """Collect all audio chunks into a single bytes object. @@ -52,10 +91,13 @@ def collect(self) -> bytes: f.write(audio) ``` """ - chunks = [] - for chunk in self._iter: - chunks.append(chunk) - return b"".join(chunks) + try: + chunks = [] + for chunk in self._iter: + chunks.append(chunk) + return b"".join(chunks) + finally: + self.close() class AsyncAudioStream: @@ -77,21 +119,59 @@ class AsyncAudioStream: # Or stream chunks manually async for chunk in await client.tts.stream(text="Hello!"): await process_chunk(chunk) + + # Use async with (or await aclose()) if you may stop early, + # so the HTTP connection is released right away + async with await client.tts.stream(text="Hello!") as stream: + async for chunk in stream: + if done(chunk): + break ``` """ - def __init__(self, async_iterator: AsyncIterator[bytes]): + def __init__( + self, + async_iterator: AsyncIterator[bytes], + *, + on_close: Optional[Callable[[], Awaitable[None]]] = None, + ): """Initialize the async audio iterator wrapper. Args: async_iterator: The underlying async iterator of audio bytes + on_close: Awaited by aclose() to release the underlying resource, + for example the open HTTP response """ self._iter = async_iterator + self._on_close = on_close + self._closed = False def __aiter__(self) -> AsyncIterator[bytes]: """Allow direct async iteration over audio chunks.""" return self._iter + async def aclose(self) -> None: + """Stop the stream and release the underlying connection. + + Safe to call more than once, and before iteration has started. + """ + if self._closed: + return + self._closed = True + try: + close_iter = getattr(self._iter, "aclose", None) + if close_iter is not None: + await close_iter() + finally: + if self._on_close is not None: + await self._on_close() + + async def __aenter__(self) -> "AsyncAudioStream": + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: + await self.aclose() + async def collect(self) -> bytes: """Collect all audio chunks into a single bytes object. @@ -109,7 +189,10 @@ async def collect(self) -> bytes: f.write(audio) ``` """ - chunks = [] - async for chunk in self._iter: - chunks.append(chunk) - return b"".join(chunks) + try: + chunks = [] + async for chunk in self._iter: + chunks.append(chunk) + return b"".join(chunks) + finally: + await self.aclose() diff --git a/src/fishaudio/resources/tts.py b/src/fishaudio/resources/tts.py index 9bc477d..8326c79 100644 --- a/src/fishaudio/resources/tts.py +++ b/src/fishaudio/resources/tts.py @@ -160,7 +160,7 @@ def _stream(): finally: response.close() - return AudioStream(_stream()) + return AudioStream(_stream(), on_close=response.close) def convert( self, @@ -475,7 +475,7 @@ async def _stream(): finally: await response.aclose() - return AsyncAudioStream(_stream()) + return AsyncAudioStream(_stream(), on_close=response.aclose) async def convert( self, diff --git a/tests/unit/test_streaming.py b/tests/unit/test_streaming.py index ba82d94..d931131 100644 --- a/tests/unit/test_streaming.py +++ b/tests/unit/test_streaming.py @@ -72,18 +72,37 @@ def test_first_chunk_arrives_before_body_is_read(self): assert list(stream) == [b"chunk-2", b"chunk-3"] assert body.closed - def test_early_break_closes_response(self): + def test_with_block_closes_after_early_break(self): body = _SyncBody(CHUNKS) tts = _sync_tts(lambda request: httpx.Response(200, stream=body)) - stream = tts.stream(text="Hello") - for _ in stream: - break - stream._iter.close() # what garbage collection does to an abandoned generator + with tts.stream(text="Hello") as stream: + for _ in stream: + break + assert not body.closed assert body.produced == 1 assert body.closed + def test_close_before_iteration_releases_response(self): + body = _SyncBody(CHUNKS) + tts = _sync_tts(lambda request: httpx.Response(200, stream=body)) + + stream = tts.stream(text="Hello") + stream.close() + stream.close() # idempotent + + assert body.produced == 0 + assert body.closed + assert list(stream) == [] + + def test_collect_closes_response(self): + body = _SyncBody(CHUNKS) + tts = _sync_tts(lambda request: httpx.Response(200, stream=body)) + + assert tts.stream(text="Hello").collect() == b"".join(CHUNKS) + assert body.closed + def test_convert_still_returns_full_audio(self): tts = _sync_tts(lambda request: httpx.Response(200, stream=_SyncBody(CHUNKS))) assert tts.convert(text="Hello") == b"".join(CHUNKS) @@ -132,18 +151,37 @@ async def test_first_chunk_arrives_before_body_is_read(self): assert rest == [b"chunk-2", b"chunk-3"] assert body.closed - async def test_early_break_closes_response(self): + async def test_async_with_closes_after_early_break(self): body = _AsyncBody(CHUNKS) tts = _async_tts(lambda request: httpx.Response(200, stream=body)) - stream = await tts.stream(text="Hello") - async for _ in stream: - break - await stream._iter.aclose() + async with await tts.stream(text="Hello") as stream: + async for _ in stream: + break + assert not body.closed assert body.produced == 1 assert body.closed + async def test_aclose_before_iteration_releases_response(self): + body = _AsyncBody(CHUNKS) + tts = _async_tts(lambda request: httpx.Response(200, stream=body)) + + stream = await tts.stream(text="Hello") + await stream.aclose() + await stream.aclose() # idempotent + + assert body.produced == 0 + assert body.closed + assert [chunk async for chunk in stream] == [] + + async def test_collect_closes_response(self): + body = _AsyncBody(CHUNKS) + tts = _async_tts(lambda request: httpx.Response(200, stream=body)) + + assert await (await tts.stream(text="Hello")).collect() == b"".join(CHUNKS) + assert body.closed + async def test_convert_still_returns_full_audio(self): tts = _async_tts(lambda request: httpx.Response(200, stream=_AsyncBody(CHUNKS))) assert await tts.convert(text="Hello") == b"".join(CHUNKS)