Skip to content

Commit 733d92c

Browse files
lumpinifclaude
andauthored
fix(tts): stream HTTP audio incrementally instead of buffering the full response (#168)
* 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 30d2713 commit 733d92c

5 files changed

Lines changed: 363 additions & 22 deletions

File tree

‎src/fishaudio/core/client_wrapper.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ def request(
122122
path: str,
123123
*,
124124
request_options: Optional[RequestOptions] = None,
125+
stream: bool = False,
125126
**kwargs: Any,
126127
) -> httpx.Response:
127128
"""
@@ -131,6 +132,9 @@ def request(
131132
method: HTTP method (GET, POST, etc.)
132133
path: API endpoint path
133134
request_options: Optional request-level overrides
135+
stream: If True, return as soon as the response headers arrive and
136+
leave the body unread. The caller must consume it with
137+
`iter_bytes()` and then call `close()` on the response.
134138
**kwargs: Additional arguments to pass to httpx.request
135139
136140
Returns:
@@ -141,6 +145,20 @@ def request(
141145
"""
142146
self._prepare_request_kwargs(request_options, kwargs)
143147

148+
if stream:
149+
timeout = kwargs.pop("timeout", httpx.USE_CLIENT_DEFAULT)
150+
http_request = self._client.build_request(
151+
method, path, timeout=timeout, **kwargs
152+
)
153+
response = self._client.send(http_request, stream=True)
154+
if not response.is_success:
155+
try:
156+
response.read()
157+
finally:
158+
response.close()
159+
_raise_for_status(response)
160+
return response
161+
144162
# Make the request
145163
response = self._client.request(method, path, **kwargs)
146164

@@ -194,6 +212,7 @@ async def request(
194212
path: str,
195213
*,
196214
request_options: Optional[RequestOptions] = None,
215+
stream: bool = False,
197216
**kwargs: Any,
198217
) -> httpx.Response:
199218
"""
@@ -203,6 +222,9 @@ async def request(
203222
method: HTTP method (GET, POST, etc.)
204223
path: API endpoint path
205224
request_options: Optional request-level overrides
225+
stream: If True, return as soon as the response headers arrive and
226+
leave the body unread. The caller must consume it with
227+
`aiter_bytes()` and then call `aclose()` on the response.
206228
**kwargs: Additional arguments to pass to httpx.request
207229
208230
Returns:
@@ -213,6 +235,20 @@ async def request(
213235
"""
214236
self._prepare_request_kwargs(request_options, kwargs)
215237

238+
if stream:
239+
timeout = kwargs.pop("timeout", httpx.USE_CLIENT_DEFAULT)
240+
http_request = self._client.build_request(
241+
method, path, timeout=timeout, **kwargs
242+
)
243+
response = await self._client.send(http_request, stream=True)
244+
if not response.is_success:
245+
try:
246+
await response.aread()
247+
finally:
248+
await response.aclose()
249+
_raise_for_status(response)
250+
return response
251+
216252
# Make the request
217253
response = await self._client.request(method, path, **kwargs)
218254

‎src/fishaudio/core/iterators.py‎

Lines changed: 94 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Audio stream wrappers with collection utilities."""
22

3-
from collections.abc import AsyncIterator, Iterator
3+
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
4+
from typing import Optional
45

56

67
class AudioStream:
@@ -21,21 +22,59 @@ class AudioStream:
2122
# Or stream chunks manually
2223
for chunk in client.tts.stream(text="Hello!"):
2324
process_chunk(chunk)
25+
26+
# Use a with-block (or call close()) if you may stop early,
27+
# so the HTTP connection is released right away
28+
with client.tts.stream(text="Hello!") as stream:
29+
for chunk in stream:
30+
if done(chunk):
31+
break
2432
```
2533
"""
2634

27-
def __init__(self, iterator: Iterator[bytes]):
35+
def __init__(
36+
self,
37+
iterator: Iterator[bytes],
38+
*,
39+
on_close: Optional[Callable[[], None]] = None,
40+
):
2841
"""Initialize the audio iterator wrapper.
2942
3043
Args:
3144
iterator: The underlying iterator of audio bytes
45+
on_close: Called by close() to release the underlying resource,
46+
for example the open HTTP response
3247
"""
3348
self._iter = iterator
49+
self._on_close = on_close
50+
self._closed = False
3451

3552
def __iter__(self) -> Iterator[bytes]:
3653
"""Allow direct iteration over audio chunks."""
3754
return self._iter
3855

56+
def close(self) -> None:
57+
"""Stop the stream and release the underlying connection.
58+
59+
Safe to call more than once, and before iteration has started.
60+
"""
61+
if self._closed:
62+
return
63+
self._closed = True
64+
try:
65+
close_iter = getattr(self._iter, "close", None)
66+
if close_iter is not None:
67+
close_iter()
68+
finally:
69+
if self._on_close is not None:
70+
self._on_close()
71+
72+
def __enter__(self) -> "AudioStream":
73+
return self
74+
75+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
76+
self.close()
77+
3978
def collect(self) -> bytes:
4079
"""Collect all audio chunks into a single bytes object.
4180
@@ -52,10 +91,13 @@ def collect(self) -> bytes:
5291
f.write(audio)
5392
```
5493
"""
55-
chunks = []
56-
for chunk in self._iter:
57-
chunks.append(chunk)
58-
return b"".join(chunks)
94+
try:
95+
chunks = []
96+
for chunk in self._iter:
97+
chunks.append(chunk)
98+
return b"".join(chunks)
99+
finally:
100+
self.close()
59101

60102

61103
class AsyncAudioStream:
@@ -77,21 +119,59 @@ class AsyncAudioStream:
77119
# Or stream chunks manually
78120
async for chunk in await client.tts.stream(text="Hello!"):
79121
await process_chunk(chunk)
122+
123+
# Use async with (or await aclose()) if you may stop early,
124+
# so the HTTP connection is released right away
125+
async with await client.tts.stream(text="Hello!") as stream:
126+
async for chunk in stream:
127+
if done(chunk):
128+
break
80129
```
81130
"""
82131

83-
def __init__(self, async_iterator: AsyncIterator[bytes]):
132+
def __init__(
133+
self,
134+
async_iterator: AsyncIterator[bytes],
135+
*,
136+
on_close: Optional[Callable[[], Awaitable[None]]] = None,
137+
):
84138
"""Initialize the async audio iterator wrapper.
85139
86140
Args:
87141
async_iterator: The underlying async iterator of audio bytes
142+
on_close: Awaited by aclose() to release the underlying resource,
143+
for example the open HTTP response
88144
"""
89145
self._iter = async_iterator
146+
self._on_close = on_close
147+
self._closed = False
90148

91149
def __aiter__(self) -> AsyncIterator[bytes]:
92150
"""Allow direct async iteration over audio chunks."""
93151
return self._iter
94152

153+
async def aclose(self) -> None:
154+
"""Stop the stream and release the underlying connection.
155+
156+
Safe to call more than once, and before iteration has started.
157+
"""
158+
if self._closed:
159+
return
160+
self._closed = True
161+
try:
162+
close_iter = getattr(self._iter, "aclose", None)
163+
if close_iter is not None:
164+
await close_iter()
165+
finally:
166+
if self._on_close is not None:
167+
await self._on_close()
168+
169+
async def __aenter__(self) -> "AsyncAudioStream":
170+
return self
171+
172+
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
173+
await self.aclose()
174+
95175
async def collect(self) -> bytes:
96176
"""Collect all audio chunks into a single bytes object.
97177
@@ -109,7 +189,10 @@ async def collect(self) -> bytes:
109189
f.write(audio)
110190
```
111191
"""
112-
chunks = []
113-
async for chunk in self._iter:
114-
chunks.append(chunk)
115-
return b"".join(chunks)
192+
try:
193+
chunks = []
194+
async for chunk in self._iter:
195+
chunks.append(chunk)
196+
return b"".join(chunks)
197+
finally:
198+
await self.aclose()

‎src/fishaudio/resources/tts.py‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -140,22 +140,27 @@ def stream(
140140

141141
payload = request.model_dump(exclude_none=True)
142142

143-
# Make request with streaming
143+
# Send the request and return once headers arrive; the body is read
144+
# lazily so chunks reach the caller as the server produces them.
144145
response = self._client.request(
145146
"POST",
146147
"/v1/tts",
147148
headers={"Content-Type": "application/msgpack", "model": model},
148149
content=ormsgpack.packb(payload),
149150
request_options=request_options,
151+
stream=True,
150152
)
151153

152154
# Create generator and wrap with AudioStream
153155
def _stream():
154-
for chunk in response.iter_bytes():
155-
if chunk:
156-
yield chunk
156+
try:
157+
for chunk in response.iter_bytes():
158+
if chunk:
159+
yield chunk
160+
finally:
161+
response.close()
157162

158-
return AudioStream(_stream())
163+
return AudioStream(_stream(), on_close=response.close)
159164

160165
def convert(
161166
self,
@@ -450,22 +455,27 @@ async def stream(
450455

451456
payload = request.model_dump(exclude_none=True)
452457

453-
# Make request with streaming
458+
# Send the request and return once headers arrive; the body is read
459+
# lazily so chunks reach the caller as the server produces them.
454460
response = await self._client.request(
455461
"POST",
456462
"/v1/tts",
457463
headers={"Content-Type": "application/msgpack", "model": model},
458464
content=ormsgpack.packb(payload),
459465
request_options=request_options,
466+
stream=True,
460467
)
461468

462469
# Create async generator and wrap with AsyncAudioStream
463470
async def _stream():
464-
async for chunk in response.aiter_bytes():
465-
if chunk:
466-
yield chunk
467-
468-
return AsyncAudioStream(_stream())
471+
try:
472+
async for chunk in response.aiter_bytes():
473+
if chunk:
474+
yield chunk
475+
finally:
476+
await response.aclose()
477+
478+
return AsyncAudioStream(_stream(), on_close=response.aclose)
469479

470480
async def convert(
471481
self,

0 commit comments

Comments
 (0)