Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,20 @@ except FishAudioError as e:
print(f"API error: {e}")
```

### Trace IDs

Responses to speech and transcription requests carry an `x-fish-trace-id` header. Include it when you contact support about a request, also one that succeeded but sounds wrong. The stream that `tts.stream()` returns has the response headers:

```python
stream = client.tts.stream(text="Hello!")
try:
audio = stream.collect()
finally:
trace_id = stream.headers.get("x-fish-trace-id") # None if not sent
```

The same `headers` attribute is on the streams of `tts.stream_with_timestamps()` and `asr.stream_websocket()` (empty until the connection opens on the first iteration), and on the results of `tts.convert_with_timestamps()` and `asr.transcribe()` (the latter also has `request_id`). `tts.convert()` returns only the audio; use `tts.stream()` as above when you need the headers. `tts.stream_websocket()` does not expose them yet.

## Resources

- **Documentation:** [SDK Guide](https://docs.fish.audio/developer-guide/sdk-guide/python/) | [API Reference](https://docs.fish.audio/api-reference/sdk/python/)
Expand Down
31 changes: 29 additions & 2 deletions src/fishaudio/core/iterators.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from typing import Optional

import httpx

from fishaudio.types.shared import _set_response_headers
from fishaudio.types.tts import (
TTSAlignment,
TTSTimestampEvent,
Expand Down Expand Up @@ -44,17 +47,22 @@ def __init__(
iterator: Iterator[bytes],
*,
on_close: Optional[Callable[[], None]] = None,
headers: Optional[httpx.Headers] = 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
headers: Headers of the HTTP response that opened the stream
"""
self._iter = iterator
self._on_close = on_close
self._closed = False
#: Headers of the HTTP response that opened the stream, for example
#: ``x-fish-trace-id``. Still readable after the stream is closed.
self.headers = headers if headers is not None else httpx.Headers()

def __iter__(self) -> Iterator[bytes]:
"""Allow direct iteration over audio chunks."""
Expand Down Expand Up @@ -141,17 +149,22 @@ def __init__(
async_iterator: AsyncIterator[bytes],
*,
on_close: Optional[Callable[[], Awaitable[None]]] = None,
headers: Optional[httpx.Headers] = 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
headers: Headers of the HTTP response that opened the stream
"""
self._iter = async_iterator
self._on_close = on_close
self._closed = False
#: Headers of the HTTP response that opened the stream, for example
#: ``x-fish-trace-id``. Still readable after the stream is closed.
self.headers = headers if headers is not None else httpx.Headers()

def __aiter__(self) -> AsyncIterator[bytes]:
"""Allow direct async iteration over audio chunks."""
Expand Down Expand Up @@ -277,17 +290,22 @@ def __init__(
iterator: Iterator[TTSTimestampEvent],
*,
on_close: Optional[Callable[[], None]] = None,
headers: Optional[httpx.Headers] = None,
):
"""Initialize the stream.

Args:
iterator: The underlying iterator of events
on_close: Called by close() to release the underlying resource,
for example the open HTTP response
headers: Headers of the HTTP response that opened the stream
"""
self._iter = iterator
self._on_close = on_close
self._closed = False
#: Headers of the HTTP response that opened the stream, for example
#: ``x-fish-trace-id``. Still readable after the stream is closed.
self.headers = headers if headers is not None else httpx.Headers()
self._timeline = _Timeline()
self._started = False

Expand Down Expand Up @@ -360,11 +378,13 @@ def collect(self) -> TTSTimestampResult:
)
try:
audio = b"".join(event.audio for event in self)
return TTSTimestampResult(
result = TTSTimestampResult(
audio=audio,
segments=self._timeline.segments,
duration=self._timeline.duration,
)
_set_response_headers(result, self.headers)
return result
finally:
self.close()

Expand Down Expand Up @@ -400,17 +420,22 @@ def __init__(
async_iterator: AsyncIterator[TTSTimestampEvent],
*,
on_close: Optional[Callable[[], Awaitable[None]]] = None,
headers: Optional[httpx.Headers] = None,
):
"""Initialize the stream.

Args:
async_iterator: The underlying async iterator of events
on_close: Awaited by aclose() to release the underlying resource,
for example the open HTTP response
headers: Headers of the HTTP response that opened the stream
"""
self._iter = async_iterator
self._on_close = on_close
self._closed = False
#: Headers of the HTTP response that opened the stream, for example
#: ``x-fish-trace-id``. Still readable after the stream is closed.
self.headers = headers if headers is not None else httpx.Headers()
self._timeline = _Timeline()
self._started = False

Expand Down Expand Up @@ -485,10 +510,12 @@ async def collect(self) -> TTSTimestampResult:
chunks = []
async for event in self:
chunks.append(event.audio)
return TTSTimestampResult(
result = TTSTimestampResult(
audio=b"".join(chunks),
segments=self._timeline.segments,
duration=self._timeline.duration,
)
_set_response_headers(result, self.headers)
return result
finally:
await self.aclose()
14 changes: 11 additions & 3 deletions src/fishaudio/resources/asr.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@
ASRTurnDetection,
TurnDetectionMode,
)
from fishaudio.types.shared import DEPRECATED_ASR_MODELS, warn_if_deprecated_model
from fishaudio.types.shared import (
DEPRECATED_ASR_MODELS,
_set_response_headers,
warn_if_deprecated_model,
)

from .asr_realtime import REALTIME_PATH, ASRRealtimeStream, AsyncASRRealtimeStream

Expand Down Expand Up @@ -150,7 +154,9 @@ def transcribe(
)

# Parse and return response
return ASRResponse.model_validate(response.json())
result = ASRResponse.model_validate(response.json())
_set_response_headers(result, response.headers)
return result

def stream_websocket(
self,
Expand Down Expand Up @@ -345,7 +351,9 @@ async def transcribe(
)

# Parse and return response
return ASRResponse.model_validate(response.json())
result = ASRResponse.model_validate(response.json())
_set_response_headers(result, response.headers)
return result

def stream_websocket(
self,
Expand Down
28 changes: 28 additions & 0 deletions src/fishaudio/resources/asr_realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,12 @@ def _upgrade_error(response: httpx.Response) -> Exception:
return _api_error(status, httpx.codes.get_reason_phrase(status) or "Upgrade failed")


def _handshake_headers(
ws: Union[WebSocketSession, AsyncWebSocketSession],
) -> httpx.Headers:
return httpx.Headers(getattr(ws.response, "headers", None))


class _Protocol:
"""Turns server messages and closes into events or exceptions (sync and async)."""

Expand Down Expand Up @@ -198,6 +204,7 @@ def __init__(self) -> None:
self._ws: Optional[WebSocketSession] = None
self._lock = threading.Lock()
self.closed = False
self.headers = httpx.Headers() # of the handshake response, once connected

def open(self, ws: WebSocketSession) -> None:
with self._lock:
Expand Down Expand Up @@ -266,6 +273,7 @@ def _iter_session(
drain_until: Optional[float] = None
try:
with connect() as ws:
link.headers = _handshake_headers(ws)
try:
try:
ws.send_bytes(config)
Expand Down Expand Up @@ -364,6 +372,15 @@ def __init__(
self._link, connect, encode_config(config), audio_stream
)

@property
def headers(self) -> httpx.Headers:
"""Headers of the handshake response, for example ``x-fish-trace-id``.

Empty until the connection opens on the first iteration; still
readable after the session has ended or failed.
"""
return self._link.headers

def __iter__(self) -> Iterator[ASRRealtimeEvent]:
return self

Expand Down Expand Up @@ -425,6 +442,7 @@ class _AsyncLink:

def __init__(self) -> None:
self._ws: Optional[AsyncWebSocketSession] = None
self.headers = httpx.Headers() # of the handshake response, once connected

def open(self, ws: AsyncWebSocketSession) -> None:
self._ws = ws
Expand Down Expand Up @@ -502,6 +520,7 @@ async def _run_session(
error: Optional[BaseException] = None
try:
async with connect() as ws:
link.headers = _handshake_headers(ws)
try:
try:
await ws.send_bytes(config)
Expand Down Expand Up @@ -622,6 +641,15 @@ def __init__(
self._reading = False
self._finished = False

@property
def headers(self) -> httpx.Headers:
"""Headers of the handshake response, for example ``x-fish-trace-id``.

Empty until the connection opens on the first iteration; still
readable after the session has ended or failed.
"""
return self._link.headers

def __aiter__(self) -> AsyncASRRealtimeStream:
return self

Expand Down
14 changes: 10 additions & 4 deletions src/fishaudio/resources/tts.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def _stream():
finally:
response.close()

return AudioStream(_stream(), on_close=response.close)
return AudioStream(_stream(), on_close=response.close, headers=response.headers)

def convert(
self,
Expand Down Expand Up @@ -397,7 +397,9 @@ def _events():
finally:
response.close()

return TTSTimestampStream(_events(), on_close=response.close)
return TTSTimestampStream(
_events(), on_close=response.close, headers=response.headers
)

def convert_with_timestamps(
self,
Expand Down Expand Up @@ -719,7 +721,9 @@ async def _stream():
finally:
await response.aclose()

return AsyncAudioStream(_stream(), on_close=response.aclose)
return AsyncAudioStream(
_stream(), on_close=response.aclose, headers=response.headers
)

async def convert(
self,
Expand Down Expand Up @@ -872,7 +876,9 @@ async def _events():
finally:
await response.aclose()

return AsyncTTSTimestampStream(_events(), on_close=response.aclose)
return AsyncTTSTimestampStream(
_events(), on_close=response.aclose, headers=response.headers
)

async def convert_with_timestamps(
self,
Expand Down
11 changes: 11 additions & 0 deletions src/fishaudio/types/asr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

from typing import Optional

import httpx
from pydantic import BaseModel

from .shared import _get_response_headers


class ASRSegment(BaseModel):
"""A timestamped segment of transcribed text.
Expand Down Expand Up @@ -55,3 +58,11 @@ class ASRResponse(BaseModel):
language_code: Optional[str] = None
request_id: Optional[str] = None
speaker_turns: Optional[list[SpeakerTurn]] = None

@property
def headers(self) -> httpx.Headers:
"""Headers of the HTTP response, for example ``x-fish-trace-id``.

Empty on a model that was created without a response.
"""
return _get_response_headers(self)
12 changes: 12 additions & 0 deletions src/fishaudio/types/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from types import FrameType
from typing import Generic, Literal, Optional, TypeVar

import httpx
from pydantic import BaseModel

# Type variable for generic pagination
Expand All @@ -24,6 +25,17 @@ class PaginatedResponse(BaseModel, Generic[T]):
items: list[T]


# Response headers of a result model are kept as a plain instance attribute,
# not as a pydantic field: they are not part of the response body, so they
# stay out of model_dump(), equality and the model's schema.
def _set_response_headers(model: BaseModel, headers: httpx.Headers) -> None:
object.__setattr__(model, "_response_headers", headers)


def _get_response_headers(model: BaseModel) -> httpx.Headers:
return model.__dict__.get("_response_headers", httpx.Headers())


# Model types
Model = Literal["s1", "s2-pro", "s2.1-pro", "s2.1-pro-free", "drama-3"]

Expand Down
11 changes: 10 additions & 1 deletion src/fishaudio/types/tts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

from typing import Annotated, Literal, Optional

import httpx
from pydantic import BaseModel, ConfigDict, Field, field_serializer

from .shared import AudioFormat, LatencyMode
from .shared import AudioFormat, LatencyMode, _get_response_headers


class ReferenceAudio(BaseModel):
Expand Down Expand Up @@ -311,3 +312,11 @@ class TTSTimestampResult(BaseModel):
audio: bytes
segments: list[TTSTimestampSegment]
duration: Optional[float] = None

@property
def headers(self) -> httpx.Headers:
"""Headers of the HTTP response, for example ``x-fish-trace-id``.

Empty on a model that was created without a response.
"""
return _get_response_headers(self)
6 changes: 5 additions & 1 deletion tests/unit/realtime_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ class ClientGone(Exception):
"""The client closed the connection."""


# Sent with every accepted handshake, as the API does.
ACCEPT_HEADERS = [(b"x-fish-trace-id", b"trace-123")]


class Connection:
"""One client connection, as seen by a server script."""

Expand Down Expand Up @@ -72,7 +76,7 @@ def _read(self) -> None:
if self._reject_status is not None:
self._write(RejectConnection(status_code=self._reject_status))
raise ClientGone
self._write(AcceptConnection())
self._write(AcceptConnection(extra_headers=ACCEPT_HEADERS))
elif isinstance(event, BytesMessage):
self._partial += bytes(event.data)
if event.message_finished:
Expand Down
Loading